From 3dd581e9cf96efc699363fc686e340c14b884132 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 06:35:52 -0800 Subject: [PATCH 01/65] 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/65] 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/65] 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/65] 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 f19df271f4898e43f092b0df86bafc5dccb89c04 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Tue, 3 Nov 2026 08:58:46 -0800 Subject: [PATCH 05/65] fix(rectMorph): a handed-in animator stays on the element through a copy dismissal CodeBunny on #9769: a dismissal onto a copy detached the animator, and a handed-in one was never attached again, so its owner's writes stopped reaching the element. Only the morph's own animator lets go now. Co-authored-by: Cindy Zhang --- packages/core/src/motion/rectMorph.test.ts | 28 ++++++++++++++++++++++ packages/core/src/motion/rectMorph.ts | 7 ++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/core/src/motion/rectMorph.test.ts b/packages/core/src/motion/rectMorph.test.ts index 15b836b616039..b78f7bb569c82 100644 --- a/packages/core/src/motion/rectMorph.test.ts +++ b/packages/core/src/motion/rectMorph.test.ts @@ -320,6 +320,34 @@ describe('createRectMorph', () => { expect(stage.get('x')).toBe(12); }); + it('leaves a handed-in animator on the element through a dismissal onto a copy', async () => { + 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: SPRING}); + await playFrame(); + const copy = element.cloneNode(true) as HTMLElement; + element.after(copy); + morph.dismiss(path, {spring: SPRING}, {target: copy}); + await playFrame(); + clock += 2000; + await vi.advanceTimersByTimeAsync(2000); + // The owner's own write still reaches the element. + stage.set({x: 12}); + expect(element.style.getPropertyValue('translate')).toContain('12px'); + morph.dispose(); + }); + 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]}); diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index af8464004a3f6..b7370b4bfbfd7 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -443,9 +443,12 @@ export function createRectMorph( // 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. + // dismissal's frames. The next present attaches the element again. A + // handed-in animator stays on the element: its owner still drives it. restoreElement(); - animator.attach(null); + if (given == null) { + animator.attach(null); + } } const closing = onElement ? animator From e3a43d0d3fade1adc4cf7cf3c2d4c670a543f06f Mon Sep 17 00:00:00 2001 From: Cindy Zhang <2781099+cixzhang@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:39:01 -0800 Subject: [PATCH 06/65] fix(motion): one timed curve keeps a retargeted velocity, for the pager and the morph CodeBunny on #9769: solveAnimatedPageScroll already played this curve and keeps the velocity of the move it retargets. timedCurve in progress.ts is now that one curve; the pager and the morph's timed motion call it, so a timed present that interrupts a dismissal keeps its velocity. The INV12 note states the system only. File header and comments trimmed. Co-authored-by: Cindy Zhang --- docs/architecture/react-component-runtime.md | 2 +- packages/core/src/motion/paging.ts | 38 ++--------- packages/core/src/motion/progress.test.ts | 9 +++ packages/core/src/motion/progress.ts | 70 +++++++++++++++----- packages/core/src/motion/rectMorph.test.ts | 8 +-- packages/core/src/motion/rectMorph.ts | 48 ++++---------- 6 files changed, 87 insertions(+), 88 deletions(-) diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md index 37e9e4bc3fbcc..2064edfb7ab6a 100644 --- a/docs/architecture/react-component-runtime.md +++ b/docs/architecture/react-component-runtime.md @@ -200,7 +200,7 @@ those contracts. `spec:AST-094` FR5) once Core has that morph; until then, the module plays 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 + translate.) 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/paging.ts b/packages/core/src/motion/paging.ts index 2cd978c7c42af..19b6ccf14c2a5 100644 --- a/packages/core/src/motion/paging.ts +++ b/packages/core/src/motion/paging.ts @@ -14,7 +14,8 @@ */ import type {MotionCurve} from './animator'; -import {cubicBezier, type BezierPoints} from './bezier'; +import type {BezierPoints} from './bezier'; +import {timedCurve} from './progress'; import {paging} from './uikit/paging'; /** @@ -113,10 +114,9 @@ export function solvePaging({ * of the table. * * `velocity` (px/s) is the velocity of a move that this one retargets. The new - * curve starts at it and still ends on `to`, at rest and on time. A new target - * keeps the current velocity, where UIKit drops it. The carry is a Hermite - * term, v × duration × u(1 − u)², less the curve's own starting slope. So a - * move from rest is the curve itself. + * curve starts at it and still ends on `to`, at rest and on time + * (`timedCurve`): a new target keeps the current velocity, where UIKit drops + * it. */ export function solveAnimatedPageScroll({ from, @@ -131,31 +131,5 @@ export function solveAnimatedPageScroll({ curve?: BezierPoints; velocity?: number; }): MotionCurve { - const duration = durationMs / 1000; - const distance = to - from; - const ease = cubicBezier(curve); - const progress = (u: number) => ease(Math.min(1, Math.max(0, u))); - // The carry, in px: the retargeted velocity over the whole duration, less - // what the curve's own starting slope already gives. - const startSlope = progress(1e-4) / 1e-4; - const carry = - velocity == null ? 0 : velocity * duration - distance * startSlope; - const at = (t: number) => { - const u = Math.min(1, Math.max(0, t / duration)); - return from + distance * progress(u) + carry * u * (1 - u) * (1 - u); - }; - return { - duration, - at, - velocity: t => { - if (t <= 0) { - return velocity ?? 0; - } - if (t >= duration) { - return 0; - } - const h = Math.min(1e-4, t / 2, (duration - t) / 2); - return (at(t + h) - at(t - h)) / (2 * h); - }, - }; + return timedCurve({from, to, durationMs, easing: curve, velocity}); } diff --git a/packages/core/src/motion/progress.test.ts b/packages/core/src/motion/progress.test.ts index a56ce3a5b74bf..1d3535ac1ca66 100644 --- a/packages/core/src/motion/progress.test.ts +++ b/packages/core/src/motion/progress.test.ts @@ -184,6 +184,15 @@ describe('timedProgressCurve', () => { expect(curve.velocity(0.1)).toBeGreaterThan(0); }); + it('starts at a retargeted velocity and still lands on time, at rest', () => { + const curve = timedProgressCurve(300, [0.25, 0.1, 0.25, 1], {velocity: 6}); + expect(curve.velocity(0)).toBe(6); + const h = 1e-4; + expect((curve.at(h) - curve.at(0)) / h).toBeCloseTo(6, 1); + expect(curve.at(0.3)).toBeCloseTo(1, 9); + expect(curve.velocity(0.3)).toBe(0); + }); + it('lands at once for a zero duration', () => { const curve = timedProgressCurve(0, [0, 0, 1, 1]); expect(curve.duration).toBe(0); diff --git a/packages/core/src/motion/progress.ts b/packages/core/src/motion/progress.ts index 11aec62e51d24..bd2cfdb68a938 100644 --- a/packages/core/src/motion/progress.ts +++ b/packages/core/src/motion/progress.ts @@ -4,8 +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), `timedProgressCurve` (the same over a duration and - * easing), `mapProgress` (one curve as a function of another), + * MotionCurve), `timedCurve` and `timedProgressCurve` (a duration and + * easing, keeping a retargeted velocity), `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) @@ -72,32 +72,72 @@ 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. + * A timed motion from `from` to `to` over `durationMs`, eased by the + * cubic-bézier `easing`: the curve a theme duration and easing play. + * + * `velocity` (units per second) is the velocity of a motion this one + * retargets. The curve starts at it and still ends on `to`, at rest and on + * time, so a new target keeps the current velocity. The carry is a Hermite + * term, v × duration × u(1 − u)², less the curve's own starting slope, so a + * motion from rest is the eased curve itself. */ -export function timedProgressCurve( - durationMs: number, - easing: BezierPoints, -): MotionCurve { +export function timedCurve({ + from, + to, + durationMs, + easing, + velocity, +}: { + from: number; + to: number; + durationMs: number; + easing: BezierPoints; + velocity?: number; +}): MotionCurve { const duration = Math.max(0, durationMs) / 1000; + if (duration === 0) { + return {duration, at: () => to, velocity: () => 0}; + } + const distance = to - from; const ease = cubicBezier(easing); - const at = (t: number) => - duration === 0 || t >= duration ? 1 : ease(Math.max(0, t) / duration); + const progress = (u: number) => ease(Math.min(1, Math.max(0, u))); + // The carry: the retargeted velocity over the whole duration, less what + // the curve's own starting slope already gives. + const startSlope = progress(1e-4) / 1e-4; + const carry = + velocity == null ? 0 : velocity * duration - distance * startSlope; + const at = (t: number) => { + const u = Math.min(1, Math.max(0, t / duration)); + return from + distance * progress(u) + carry * u * (1 - u) * (1 - u); + }; return { duration, at, velocity: t => { - if (duration === 0 || t >= duration) { + if (t <= 0) { + return velocity ?? 0; + } + if (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); + const h = Math.min(1e-4, t / 2, (duration - t) / 2); + return (at(t + h) - at(t - h)) / (2 * h); }, }; } +/** + * `timedCurve` as a progress from 0 to 1, its velocity in progress per + * second: the timed counterpart of `progressCurve`. + */ +export function timedProgressCurve( + durationMs: number, + easing: BezierPoints, + {velocity}: {velocity?: number} = {}, +): MotionCurve { + return timedCurve({from: 0, to: 1, durationMs, easing, velocity}); +} + /** * 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 index b78f7bb569c82..26137a9ce3b93 100644 --- a/packages/core/src/motion/rectMorph.test.ts +++ b/packages/core/src/motion/rectMorph.test.ts @@ -272,16 +272,16 @@ describe('createRectMorph', () => { } }); - it('presents on a theme timing: its duration and easing as given, from rest', async () => { + it('presents on a theme timing: its duration and easing as given, from the velocity it is given', 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. + // A timed present keeps the velocity it is given (a new target keeps the + // current velocity) and still lands on time. morph.present(path, {duration: 300, easing}, {velocity: 6}); await playFrame(); expect(live(element, 'scale').length).toBe(1); - const progress = timedProgressCurve(300, easing); + const progress = timedProgressCurve(300, easing, {velocity: 6}); const start = clock; for (const t of [0, 0.05, 0.12, 0.2, 0.29]) { clock = start + t * 1000; diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index b7370b4bfbfd7..b53d97efb6c3f 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -15,29 +15,6 @@ * 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 @@ -71,7 +48,6 @@ 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'; @@ -134,8 +110,9 @@ 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`). + * release plays a spring. Either starts at the velocity it is given + * (`RectMorphPlayOptions.velocity`), so a new target keeps the current + * velocity. */ export type RectMorphMotion = | {readonly duration: number; readonly easing: MotionCurvePoints} @@ -146,9 +123,9 @@ export type RectMorphMotion = */ 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. + * Progress per second to start with (a finger's release). By default the + * velocity of what is on screen, projected on the path, so a motion that + * interrupts another keeps its velocity. */ velocity?: number; /** @@ -303,7 +280,8 @@ export function createRectMorph( release(target); }; - // Once a present settles on identity, nothing of the morph's stays inline. + // iOS Safari does not scroll a finger through an element that keeps a + // `scale`, even at 1. Clear it once the present settles. const retire = () => { const at = now(); const identity = @@ -320,11 +298,9 @@ export function createRectMorph( } }; - // 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. + // A path with no opacity gives the Reduced Motion cross-fade nothing to + // read. Treat it as an entrance on a present and an exit on a dismissal. A + // caller's `crossfadeAs` wins, and `'move'` keeps the animator's dip. const playOptions = ( play: RectMorphPlayOptions, path: MorphPath, @@ -352,7 +328,7 @@ export function createRectMorph( ) => 'spring' in motion ? progressCurve(resolveMotion(on, motion.spring), {velocity}) - : timedProgressCurve(motion.duration, motion.easing); + : timedProgressCurve(motion.duration, motion.easing, {velocity}); const curvesFor = ( on: Element, From c99210aa453fef362051d82a59894263ad31886e Mon Sep 17 00:00:00 2001 From: Cindy Zhang <2781099+cixzhang@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:06:47 -0800 Subject: [PATCH 07/65] fix(rectMorph): a timed motion from rest plays its easing as given CodeBunny on #9769: with nothing in flight the morph handed timedCurve a velocity of 0, which it treats as a retarget and uses to cancel the easing's starting slope. Only a motion in flight hands its velocity on now; tests check a present from rest and a dismissal from a settled present against the easing itself. Header and comments shortened. Co-authored-by: Cindy Zhang --- packages/core/src/motion/rectMorph.test.ts | 31 ++++++++++++++++++ packages/core/src/motion/rectMorph.ts | 37 +++++++++++----------- 2 files changed, 50 insertions(+), 18 deletions(-) diff --git a/packages/core/src/motion/rectMorph.test.ts b/packages/core/src/motion/rectMorph.test.ts index 26137a9ce3b93..4a26cf964db2f 100644 --- a/packages/core/src/motion/rectMorph.test.ts +++ b/packages/core/src/motion/rectMorph.test.ts @@ -15,6 +15,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {createMotionAnimator} from './animator'; +import {cubicBezier} from './bezier'; import {progressCurve, timedProgressCurve} from './progress'; import { createRectMorph, @@ -289,6 +290,36 @@ describe('createRectMorph', () => { } }); + it('plays a timed present from rest on its easing as given', async () => { + const {morph} = setup(); + const path = lerpPath(SQUARE, BOX); + const easing = [0, 0, 0.58, 1] as const; + const ease = cubicBezier(easing); + morph.present(path, {duration: 250, easing}); + await playFrame(); + const start = clock; + for (const t of [0.02, 0.05, 0.1, 0.2]) { + clock = start + t * 1000; + expectRect(morph.presentedRect()!, path.rectAt(ease(t / 0.25)), 0.01); + } + }); + + it('plays a timed dismissal from a settled present on its easing as given', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX); + morph.present(path, {spring: SPRING}); + await settle(2000); + const easing = [0, 0, 0.58, 1] as const; + const ease = cubicBezier(easing); + morph.dismiss(path, {duration: 250, easing}, {target: copyOf(element)}); + await playFrame(); + const start = clock; + for (const t of [0.02, 0.05, 0.1, 0.2]) { + clock = start + t * 1000; + expectRect(morph.presentedRect()!, path.rectAt(1 - ease(t / 0.25)), 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. diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index b53d97efb6c3f..d7564fb169638 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -10,10 +10,8 @@ * @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 + * @position Motion building block, internal to core: grow out of a source + * rect and shrink back into it * * SYNC: When modified, update: * - /packages/core/src/motion/rectMorph.test.ts @@ -250,9 +248,8 @@ export function createRectMorph( } }; - // 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. + // At rest the element needs no compositing layer, so set the values without + // promoting it. const restoreElement = () => { animator.set( ownsOpacity @@ -317,14 +314,14 @@ export function createRectMorph( : 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. + // A spring goes through `resolveMotion`. A motion role resolves to its + // table value, and a bare spring comes back as given. `velocity` is + // undefined when nothing was moving: a timed motion then plays its easing + // as given. const progressFor = ( on: Element, motion: RectMorphMotion, - velocity: number, + velocity: number | undefined, ) => 'spring' in motion ? progressCurve(resolveMotion(on, motion.spring), {velocity}) @@ -335,7 +332,7 @@ export function createRectMorph( path: MorphPath, motion: RectMorphMotion, play: RectMorphPlayOptions, - velocity: number, + velocity: number | undefined, ) => { const progress = progressFor(on, motion, velocity); const fade = @@ -348,7 +345,7 @@ export function createRectMorph( const from = exiting ?? (presenting != null && box != null ? {animator, box} : null); let start = path; - let velocity = play.velocity ?? 0; + let velocity = play.velocity; let opacity: number | undefined; if (from != null) { opacity = from.animator.get('opacity', at); @@ -394,9 +391,14 @@ export function createRectMorph( opacity, 'source', ); + // A settled present is not moving: only a motion in flight hands its + // velocity on. + const inFlight = exiting != null || presenting != null; const velocity = play.velocity ?? - presentedProgressVelocity(from.animator, channelsOf(back), at); + (inFlight + ? presentedProgressVelocity(from.animator, channelsOf(back), at) + : undefined); // 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. @@ -416,9 +418,8 @@ export function createRectMorph( 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 + // of the layer its presentation promoted, in this task. Otherwise the + // promotion's linger ends later, with a style write inside the // dismissal's frames. The next present attaches the element again. A // handed-in animator stays on the element: its owner still drives it. restoreElement(); From 3272828782bdec02835551a2c12ba7fddaf64ca6 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 11:20:20 -0800 Subject: [PATCH 08/65] docs(rectMorph): the timing follows the component's motion record The type's doc, the example and the changeset name no rule of their own about which input plays which timing: each play takes the timing the adopting component's motion record names (AST-094 FR45). Co-authored-by: Christopher Chedeau --- .changeset/motion-rect-morph.md | 2 +- packages/core/src/motion/rectMorph.ts | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.changeset/motion-rect-morph.md b/.changeset/motion-rect-morph.md index 0192c46f8c2cd..e7003e85f8e4b 100644 --- a/.changeset/motion-rect-morph.md +++ b/.changeset/motion-rect-morph.md @@ -2,6 +2,6 @@ '@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. +[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. Each play takes the timing the component's motion record names (AST-094 FR45): a duration and easing, or a spring, starting from the velocity it is given. 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/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index d7564fb169638..b673af8d5b8ad 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -106,11 +106,11 @@ function startValues(path: MorphPath, opacity?: number): MotionValues { 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. Either starts at the velocity it is given - * (`RectMorphPlayOptions.velocity`), so a new target keeps the current - * velocity. + * How a present or a dismissal is timed: a duration (ms) and easing, or a + * spring. The timing follows the component's motion record (`spec:AST-094` + * FR45); the morph has no rule of its own about which input plays which. + * Either starts at the velocity it is given (`RectMorphPlayOptions.velocity`), + * so a new target keeps the current velocity. */ export type RectMorphMotion = | {readonly duration: number; readonly easing: MotionCurvePoints} @@ -211,10 +211,10 @@ function defaultNow(): number { * ``` * 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}); + * // Each play takes the timing the component's motion record names. + * morph.present(path, presentMotion); + * // A dismissal onto a copy placed where the menu stands keeps its velocity. + * morph.dismiss(path, dismissMotion, {target: copy, velocity}); * ``` * * An element that already has an animator (a zoom stage's pinch and pan) From 3fdca8fc1061ee9b2e42d2f814a57103abd63b3a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 19:38:55 -0800 Subject: [PATCH 09/65] fix(rectMorph): AST-094 links the morph; the proof imports a safe test The morph's comment cited AST-094 FR45 as its only link to that record. AST-094 now lists the file, and the comment keeps the fact without the citation. The proof imports `test` from the a11y-spec package, whose contexts reach no remote host, as main's lint asks. --- docs/specs/AST-094-touch-presentations/spec.md | 1 + .../motion/__tests__/rectMorph.interaction.browser.spec.ts | 2 +- packages/core/src/motion/rectMorph.ts | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 068161c04fb61..05832f7f5e23b 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -35,6 +35,7 @@ verified_by: "packages/core/src/Layer/holdEntranceInput.ts", "packages/core/src/Layer/inputHold.ts", "packages/core/src/hooks/usePager.ts", + "packages/core/src/motion/rectMorph.ts", "packages/core/src/motion/uikit/segmented.ts", "packages/core/src/motion/uikit/slider.ts" ] diff --git a/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts index f4305542366ce..52070f692e438 100644 --- a/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts +++ b/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts @@ -25,7 +25,7 @@ import { traceRendering, trackMarker, } from '@astryxdesign/interaction-harness'; -import {expect, test, type Page} from '@playwright/test'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; import {build} from 'esbuild'; // The page's `Motion` global (the bundle) is declared beside the animator's // proofs, in animator.interaction.browser.spec.ts. diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index 8daa485bb0354..f96ac28428a20 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -107,8 +107,8 @@ const INLINE_PROPERTIES = ['translate', 'scale', 'transform-origin'] as const; /** * How a present or a dismissal is timed: a duration (ms) and easing, or a - * spring. The timing follows the component's motion record (`spec:AST-094` - * FR45); the morph has no rule of its own about which input plays which. + * spring. The timing follows the component's motion record. The morph has no + * rule of its own about which input plays which. * Either starts at the velocity it is given (`RectMorphPlayOptions.velocity`), * so a new target keeps the current velocity. */ From d4903e2729a5f064954a9b63fc3f94266a36e489 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 20:06:16 -0800 Subject: [PATCH 10/65] test(SnapPaging): the pager's bundle lists the progress module The pager's timed settle takes its curve from motion/progress.ts, so the hook adds that module over Carousel alone. The bundle test lists it as pager code. --- scripts/snap-paging-bundle.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/snap-paging-bundle.test.mjs b/scripts/snap-paging-bundle.test.mjs index 6187b08061406..6241842062ca8 100644 --- a/scripts/snap-paging-bundle.test.mjs +++ b/scripts/snap-paging-bundle.test.mjs @@ -30,7 +30,7 @@ const PAGER_CODE = new RegExp( 'hooks/usePager\\.ts', 'SnapPaging/SnapPaging\\.ts', 'gestures/', - 'motion/(animator|paging|presentation|projection|reducedMotionPlan|resolveMotion|resolveSnapPoint|roleValue|rubberBand|spring|themeTempo)\\.ts', + 'motion/(animator|paging|presentation|progress|projection|reducedMotionPlan|resolveMotion|resolveSnapPoint|roleValue|rubberBand|spring|themeTempo)\\.ts', 'motion/uikit/(gestures|paging|scroll)\\.ts', 'Layer/inputHold\\.ts', 'utils/(clickGuard|isApplePlatform|primaryClick|selectionLock)\\.ts', From 1b794afbdb8d10e9d06e0d3ac2e4e66842df8682 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 23:50:34 -0800 Subject: [PATCH 11/65] test(motion): the popover's proofs read Popover's live geometry The morph's popover proofs played a copy of Popover's growth that had drifted: it lacked the overlap rule, so an overlapping popover grew from its left edge where Popover grows from its top. The proofs now import popoverCollapsedState, popoverFrame and frameOf from Popover. A new overlapping case, which the deleted copy fails, pins the growth from the top edge. --- packages/core/src/motion/morphPath.test.ts | 146 +++++++++------------ 1 file changed, 61 insertions(+), 85 deletions(-) diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts index 2f1f7e630da21..ba05771518861 100644 --- a/packages/core/src/motion/morphPath.test.ts +++ b/packages/core/src/motion/morphPath.test.ts @@ -21,6 +21,12 @@ import { type MorphPath, type MorphRect, } from './morphPath'; +import { + frameOf, + popoverCollapsedState, + popoverFrame, + type PopoverCollapsedState, +} from '../Popover/popoverSurfaceFrame'; import {progressCurve} from './progress'; const SPRING = {response: 0.4, dampingRatio: 1}; @@ -148,67 +154,43 @@ describe('morphCurves', () => { // 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 is on main, so its proofs read its live geometry. -/** 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, - }; - }; +/** Popover's live geometry, in the morph's rect form. */ +function popoverState(surface: MorphRect, source: MorphRect) { + const box = (rect: MorphRect) => ({ + left: rect.x, + top: rect.y, + width: rect.width, + height: rect.height, + }); + return popoverCollapsedState({surface: box(surface), source: box(source)}); +} + +/** The rect a Popover frame shows: its scale about its origin. */ +function popoverRect( + surface: MorphRect, + state: PopoverCollapsedState, + frame: {scaleX: number; scaleY: number}, +): MorphRect { return { - state, - rectAt: (p: number) => - frameRect( - state.scale + (1 - state.scale) * p, - state.length + (1 - state.length) * p, - ), - frameRect, + x: surface.x + state.originX * (1 - frame.scaleX), + y: surface.y + state.originY * (1 - frame.scaleY), + width: surface.width * frame.scaleX, + height: surface.height * frame.scaleY, }; } +function popoverPath(surface: MorphRect, state: PopoverCollapsedState) { + return edgeGrowPath({ + box: surface, + origin: {x: state.originX, y: state.originY}, + axis: state.axis, + collapsedScale: state.scale, + collapsedLength: state.length, + }); +} + /** DropdownMenu (#8080, menuSurfaceMotion.ts): menuCollapsedState, scaled per axis about its origin. */ function menuModel(surface: MorphRect, anchor: {x: number; y: number}) { const collapsedSize = 22; @@ -323,56 +305,50 @@ describe('the presentations that move onto the morph are the same rect at every 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}, + overlapping: {x: 41, y: 100, width: 140, height: 200}, }; + // A popover that overlaps its source grows from below: from its top edge. + expect(popoverState(surfaces.overlapping, source)).toMatchObject({ + axis: 'y', + originY: 0, + }); 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, - }); + const state = popoverState(surface, source); + const path = popoverPath(surface, state); for (const p of PROGRESSES) { - expectRect(path.rectAt(p), model.rectAt(p), 0.5); - expect(path.opacityAt!(p)).toBeCloseTo(p, 9); + const frame = popoverFrame(state, p); + expectRect(path.rectAt(p), popoverRect(surface, state, frame), 0.5); + expect(path.opacityAt!(p)).toBeCloseTo(frame.opacity, 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, { + const state = popoverState(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, - }); + const path = popoverPath(surface, state); + const rectOf = (scale: number, length: number) => + popoverRect( + surface, + state, + frameOf({scale, length, opacity: 1}, state.axis), + ); // Mid-dismissal: scale 0.4, length 0.6 (readState), opacity 0.5. - const onScreen = model.frameRect(0.4, 0.6); + const onScreen = rectOf(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, - ); + // Popover's curves: each of scale, length and opacity on a line. + expectRect(back.rectAt(p), rectOf(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, - ), + rectOf(0.4 + (state.scale - 0.4) * p, 0.6 + (state.length - 0.6) * p), 0.5, ); expect(away.opacityAt!(p)).toBeCloseTo(0.5 - 0.5 * p, 9); From 3bfa524a35b90ffdc06a037bee1e60c2f83fe836 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:08:46 -0800 Subject: [PATCH 12/65] refactor(motion): one eased progress, with a retargeted velocity The rect morph's timedProgressCurve played, from rest, the curve that easedProgress already plays for Popover, SegmentedControl and the layout glide. easedProgress moves into progress.ts and takes an optional velocity: the Hermite carry that the pager and the morph use. From rest its values do not change. Its velocity is a central difference that stays inside the curve, and from rest it starts on the curve's own slope. timedProgressCurve goes, and timedCurve maps easedProgress onto values, keeping only its carry for no distance. --- .../core/src/Popover/popoverSurfaceMotion.ts | 8 +- .../useSegmentedSelectionMotion.ts | 3 +- packages/core/src/motion/paging.test.ts | 6 +- packages/core/src/motion/progress.test.ts | 89 ++++++++++- packages/core/src/motion/progress.ts | 149 ++++++++++++------ packages/core/src/motion/rectMorph.test.ts | 4 +- packages/core/src/motion/rectMorph.ts | 7 +- .../src/motion/themeTiming.server.test.ts | 1 - packages/core/src/motion/themeTiming.test.ts | 36 +---- packages/core/src/motion/themeTiming.ts | 44 +----- 10 files changed, 203 insertions(+), 144 deletions(-) diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.ts index fb3ff9f304a2a..8d81b05bd0b0c 100644 --- a/packages/core/src/Popover/popoverSurfaceMotion.ts +++ b/packages/core/src/Popover/popoverSurfaceMotion.ts @@ -27,12 +27,8 @@ import { type MotionHandle, } from '../motion/animator'; import {holdInput} from '../Layer/inputHold'; -import {mapProgress, mapRange} from '../motion/progress'; -import { - easedProgress, - readThemeTiming, - type ThemeTimingTokens, -} from '../motion/themeTiming'; +import {easedProgress, mapProgress, mapRange} from '../motion/progress'; +import {readThemeTiming, type ThemeTimingTokens} from '../motion/themeTiming'; import {placePopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; import { frameOf, diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts index 5d760e4b22552..3c4a4462cb469 100644 --- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts @@ -41,7 +41,8 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {observeResize} from '../utils/sharedResizeObserver'; import {titleOfSegment} from '../privateAttributes/segmentTitle.stylex'; import {mapProgress, mapRange} from '../motion/progress'; -import {easedProgress, readThemeTiming} from '../motion/themeTiming'; +import {easedProgress} from '../motion/progress'; +import {readThemeTiming} from '../motion/themeTiming'; import {useSegmentedTouchTracking} from './useSegmentedTouchTracking'; /** The segments, in DOM order. */ diff --git a/packages/core/src/motion/paging.test.ts b/packages/core/src/motion/paging.test.ts index 7f58d9647c06b..04b0683b5e6e5 100644 --- a/packages/core/src/motion/paging.test.ts +++ b/packages/core/src/motion/paging.test.ts @@ -414,7 +414,11 @@ describe('solveAnimatedPageScroll: setContentOffset(_:animated:)', () => { expect(curve.duration).toBe(0.3); expect(curve.at(0.3)).toBe(distance); expect(curve.velocity(0.3)).toBe(0); - expect(curve.velocity(0)).toBe(0); + // From rest it starts on its curve's own slope. + expect(curve.velocity(0)).toBeCloseTo( + (curve.at(1e-6) - curve.at(0)) / 1e-6, + 2, + ); } }); diff --git a/packages/core/src/motion/progress.test.ts b/packages/core/src/motion/progress.test.ts index 1d3535ac1ca66..e90fb12d92266 100644 --- a/packages/core/src/motion/progress.test.ts +++ b/packages/core/src/motion/progress.test.ts @@ -2,12 +2,14 @@ import {describe, expect, it} from 'vitest'; import type {MotionProperty} from './animator'; +import {cubicBezier} from './bezier'; import { + easedProgress, mapProgress, mapRange, presentedProgressVelocity, progressCurve, - timedProgressCurve, + timedCurve, type ProgressChannel, } from './progress'; import {solveSpring, toSpring} from './spring'; @@ -172,9 +174,39 @@ describe('presentedProgressVelocity', () => { }); }); -describe('timedProgressCurve', () => { +describe('easedProgress', () => { + it('eases from 0 to 1 over its length, and a curve of no length is at its end', () => { + const curve = easedProgress(0.2, x => x * x); + expect(curve.duration).toBe(0.2); + expect(curve.at(0)).toBe(0); + expect(curve.at(0.1)).toBeCloseTo(0.25, 6); + expect(curve.at(0.2)).toBe(1); + expect(curve.velocity(0.1)).toBeCloseTo(5, 3); + expect(curve.velocity(0.2)).toBe(0); + const none = easedProgress(0, x => x); + expect(none.at(0)).toBe(1); + expect(none.velocity(0)).toBe(0); + }); + + it('with jumps, a jump carries no speed and a smooth stretch keeps its slope', () => { + const steps = (x: number) => Math.floor(4 * x) / 4; + // Without the option, the jump at a quarter of 300 ms reads as a spike. + expect(easedProgress(0.3, steps).velocity(0.075)).toBeGreaterThan(100); + const jumping = easedProgress(0.3, steps, {jumps: true}); + for (const t of [0, 0.0749, 0.075, 0.0751, 0.15, 0.225, 0.2995]) { + expect(jumping.velocity(t), `${t} s`).toBe(0); + } + expect( + easedProgress(0.2, x => x * x, {jumps: true}).velocity(0.1), + ).toBeCloseTo(5, 1); + }); +}); + +describe('easedProgress with a retargeted velocity', () => { + const EASE = cubicBezier([0.25, 0.1, 0.25, 1]); + 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]); + const curve = easedProgress(0.3, EASE); expect(curve.duration).toBeCloseTo(0.3, 9); expect(curve.at(0)).toBeCloseTo(0, 9); expect(curve.at(0.15)).toBeGreaterThan(0.5); @@ -185,17 +217,64 @@ describe('timedProgressCurve', () => { }); it('starts at a retargeted velocity and still lands on time, at rest', () => { - const curve = timedProgressCurve(300, [0.25, 0.1, 0.25, 1], {velocity: 6}); + const curve = easedProgress(0.3, EASE, {velocity: 6}); expect(curve.velocity(0)).toBe(6); const h = 1e-4; expect((curve.at(h) - curve.at(0)) / h).toBeCloseTo(6, 1); expect(curve.at(0.3)).toBeCloseTo(1, 9); expect(curve.velocity(0.3)).toBe(0); + // Its own velocity numerics follow the curve it plays. + for (const t of [0.01, 0.1, 0.2, 0.29]) { + expect(curve.velocity(t), `${t} s`).toBeCloseTo( + (curve.at(t + 1e-6) - curve.at(t - 1e-6)) / 2e-6, + 1, + ); + } + }); + + it('from rest is the eased curve itself', () => { + const curve = easedProgress(0.3, EASE, {}); + for (const t of [0, 0.05, 0.15, 0.25]) { + expect(curve.at(t)).toBe(EASE(t / 0.3)); + } }); it('lands at once for a zero duration', () => { - const curve = timedProgressCurve(0, [0, 0, 1, 1]); + const curve = easedProgress(0, EASE, {velocity: 6}); expect(curve.duration).toBe(0); expect(curve.at(0)).toBe(1); }); }); + +describe('timedCurve', () => { + it('is easedProgress on its values, with the velocity in those units', () => { + const curve = timedCurve({ + from: 100, + to: 400, + durationMs: 300, + easing: [0.25, 0.1, 0.25, 1], + velocity: 1800, + }); + const progress = easedProgress(0.3, cubicBezier([0.25, 0.1, 0.25, 1]), { + velocity: 6, + }); + for (const t of [0, 0.05, 0.15, 0.3]) { + expect(curve.at(t)).toBeCloseTo(100 + 300 * progress.at(t), 9); + } + expect(curve.velocity(0)).toBe(1800); + }); + + it('with no distance, only the carry plays and it comes back on time', () => { + const curve = timedCurve({ + from: 50, + to: 50, + durationMs: 300, + easing: [0, 0, 1, 1], + velocity: 600, + }); + expect(curve.velocity(0)).toBe(600); + expect(curve.at(0.1)).toBeGreaterThan(50); + expect(curve.at(0.3)).toBe(50); + expect(curve.velocity(0.3)).toBe(0); + }); +}); diff --git a/packages/core/src/motion/progress.ts b/packages/core/src/motion/progress.ts index bd2cfdb68a938..ce29886e532f6 100644 --- a/packages/core/src/motion/progress.ts +++ b/packages/core/src/motion/progress.ts @@ -3,12 +3,13 @@ /** * @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), `timedCurve` and `timedProgressCurve` (a duration and - * easing, keeping a retargeted velocity), `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) + * @output Exports `progressCurve`, a spring's progress from 0 to 1 as a + * MotionCurve. Exports `easedProgress`, a duration and easing that keeps a + * retargeted velocity, and `timedCurve`, that curve on values. Exports + * `mapProgress`, one curve as a function of another, and `mapRange`, the + * clamped linear map most companions use. Exports + * `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 @@ -71,15 +72,71 @@ export function progressCurve( }; } +/** The step that reads an easing's starting slope. */ +const START_STEP = 1e-4; + /** - * A timed motion from `from` to `to` over `durationMs`, eased by the - * cubic-bézier `easing`: the curve a theme duration and easing play. + * The eased progress from 0 to 1 over `seconds`, as a MotionCurve whose + * velocity is in progress per second. A curve of no length is at its end. + * With `jumps`, a jump in the easing, as in `steps()`, carries no speed. The + * gentler of the slopes just before and just after counts. * - * `velocity` (units per second) is the velocity of a motion this one - * retargets. The curve starts at it and still ends on `to`, at rest and on + * `velocity` (progress per second) is the velocity of a motion this one + * retargets. The curve starts at it and still ends at 1, at rest and on * time, so a new target keeps the current velocity. The carry is a Hermite - * term, v × duration × u(1 − u)², less the curve's own starting slope, so a - * motion from rest is the eased curve itself. + * term, v × seconds × u(1 − u)², less the easing's own starting slope. A + * motion from rest is then the eased curve itself. + */ +export function easedProgress( + seconds: number, + ease: (x: number) => number, + { + jumps = false, + velocity, + }: {readonly jumps?: boolean; readonly velocity?: number} = {}, +): MotionCurve { + const carry = + velocity == null || seconds <= 0 + ? 0 + : velocity * seconds - ease(START_STEP) / START_STEP; + const at = (t: number) => { + if (seconds <= 0 || t >= seconds) { + return 1; + } + const u = Math.max(0, t) / seconds; + return carry === 0 ? ease(u) : ease(u) + carry * u * (1 - u) * (1 - u); + }; + return { + duration: seconds, + at, + velocity: t => { + if (seconds <= 0 || t >= seconds) { + return 0; + } + if (t <= 0) { + // From rest, the curve's own starting slope, to second order. + const h = Math.min(1e-3, seconds / 100); + return velocity ?? (4 * at(h) - 3 * at(0) - at(2 * h)) / (2 * h); + } + // A central difference that stays inside the curve. + const h = Math.min(1e-4, t / 2, (seconds - t) / 2); + if (!jumps) { + return (at(t + h) - at(t - h)) / (2 * h); + } + const here = at(t); + const before = (here - at(t - h)) / h; + const after = (at(t + h) - here) / h; + return Math.abs(after) < Math.abs(before) ? after : before; + }, + }; +} + +/** + * A timed motion from `from` to `to` over `durationMs`, eased by the + * cubic-bézier `easing`: `easedProgress` on those values. `velocity` (units + * per second) is the velocity of a motion this one retargets, which the + * curve starts at. With no distance to cover, only that carry plays: the + * curve leaves and comes back to `to`, at rest and on time. */ export function timedCurve({ from, @@ -94,50 +151,40 @@ export function timedCurve({ easing: BezierPoints; velocity?: number; }): MotionCurve { - const duration = Math.max(0, durationMs) / 1000; - if (duration === 0) { - return {duration, at: () => to, velocity: () => 0}; - } + const seconds = Math.max(0, durationMs) / 1000; const distance = to - from; - const ease = cubicBezier(easing); - const progress = (u: number) => ease(Math.min(1, Math.max(0, u))); - // The carry: the retargeted velocity over the whole duration, less what - // the curve's own starting slope already gives. - const startSlope = progress(1e-4) / 1e-4; - const carry = - velocity == null ? 0 : velocity * duration - distance * startSlope; - const at = (t: number) => { - const u = Math.min(1, Math.max(0, t / duration)); - return from + distance * progress(u) + carry * u * (1 - u) * (1 - u); - }; + if (distance === 0 && seconds > 0 && velocity != null && velocity !== 0) { + const carry = velocity * seconds; + return { + duration: seconds, + at: t => { + const u = Math.min(1, Math.max(0, t / seconds)); + return from + carry * u * (1 - u) * (1 - u); + }, + velocity: t => { + if (t <= 0) { + return velocity; + } + if (t >= seconds) { + return 0; + } + const u = t / seconds; + return velocity * (1 - u) * (1 - 3 * u); + }, + }; + } + const progress = easedProgress( + seconds, + cubicBezier(easing), + velocity == null || distance === 0 ? {} : {velocity: velocity / distance}, + ); return { - duration, - at, - velocity: t => { - if (t <= 0) { - return velocity ?? 0; - } - if (t >= duration) { - return 0; - } - const h = Math.min(1e-4, t / 2, (duration - t) / 2); - return (at(t + h) - at(t - h)) / (2 * h); - }, + duration: seconds, + at: t => from + distance * progress.at(t), + velocity: t => distance * progress.velocity(t), }; } -/** - * `timedCurve` as a progress from 0 to 1, its velocity in progress per - * second: the timed counterpart of `progressCurve`. - */ -export function timedProgressCurve( - durationMs: number, - easing: BezierPoints, - {velocity}: {velocity?: number} = {}, -): MotionCurve { - return timedCurve({from: 0, to: 1, durationMs, easing, velocity}); -} - /** * 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 index 111beaa1da8ed..2e75ae58d12e7 100644 --- a/packages/core/src/motion/rectMorph.test.ts +++ b/packages/core/src/motion/rectMorph.test.ts @@ -16,7 +16,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {createMotionEngine} from './animator'; import {cubicBezier} from './bezier'; -import {progressCurve, timedProgressCurve} from './progress'; +import {easedProgress, progressCurve} from './progress'; import { createRectMorph, edgeGrowPath, @@ -282,7 +282,7 @@ describe('createRectMorph', () => { morph.present(path, {duration: 300, easing}, {velocity: 6}); await playFrame(); expect(live(element, 'scale').length).toBe(1); - const progress = timedProgressCurve(300, easing, {velocity: 6}); + const progress = easedProgress(0.3, cubicBezier(easing), {velocity: 6}); const start = clock; for (const t of [0, 0.05, 0.12, 0.2, 0.29]) { clock = start + t * 1000; diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts index f96ac28428a20..a6c311344930e 100644 --- a/packages/core/src/motion/rectMorph.ts +++ b/packages/core/src/motion/rectMorph.ts @@ -28,11 +28,12 @@ import { type MotionValues, } from './animator'; import { + easedProgress, presentedProgressVelocity, progressCurve, - timedProgressCurve, type ProgressChannel, } from './progress'; +import {cubicBezier} from './bezier'; import { lerpPath, morphCurves, @@ -325,7 +326,9 @@ export function createRectMorph( ) => 'spring' in motion ? progressCurve(resolveMotion(on, motion.spring), {velocity}) - : timedProgressCurve(motion.duration, motion.easing, {velocity}); + : easedProgress(motion.duration / 1000, cubicBezier(motion.easing), { + velocity, + }); const curvesFor = ( on: Element, diff --git a/packages/core/src/motion/themeTiming.server.test.ts b/packages/core/src/motion/themeTiming.server.test.ts index 8996658744248..0adcec7a7103e 100644 --- a/packages/core/src/motion/themeTiming.server.test.ts +++ b/packages/core/src/motion/themeTiming.server.test.ts @@ -38,7 +38,6 @@ describe('the theme-timing reader on the server', () => { it('imports with no window or document', () => { expect(importOnServer(path.join(__dirname, 'themeTiming.ts'))).toEqual([ 'declaredTimingTokens', - 'easedProgress', 'readThemeTiming', 'readThemeTokenText', 'readThemeTokens', diff --git a/packages/core/src/motion/themeTiming.test.ts b/packages/core/src/motion/themeTiming.test.ts index e07eb74f9103d..f6e3c280e0b80 100644 --- a/packages/core/src/motion/themeTiming.test.ts +++ b/packages/core/src/motion/themeTiming.test.ts @@ -2,13 +2,12 @@ /** * @file themeTiming.test.ts - * @input vitest (jsdom), themeTiming's readers and easedProgress, the - * theme's duration and easing defaults + * @input vitest (jsdom), themeTiming's readers, the theme's duration and + * easing defaults * @output Checks how a motion reads its timing: from the element's own * transition, and from tokens set where the element is or at their * defaults. A default that refers to a token reads it there. Also checks - * the values that give no curve, the progress velocity and easedProgress's - * curve, and that a jump in an easing carries no speed. jsdom resolves no + * the values that give no curve and the progress velocity. jsdom resolves no * `calc()` and plays no `linear()` or `steps()`: a stand-in plays one, and * the browser proof covers both. * @position Testing; validates themeTiming.ts @@ -19,7 +18,6 @@ import {cubicBezier} from './bezier'; import {parseCssEasing} from './roles'; import { declaredTimingTokens, - easedProgress, readThemeTiming, readThemeTokens, resolveTiming, @@ -203,31 +201,3 @@ describe('resolveTiming', () => { expect(document.body.children).toHaveLength(1); }); }); - -describe('easedProgress', () => { - it('eases from 0 to 1 over its length, and a curve of no length is at its end', () => { - const curve = easedProgress(0.2, x => x * x); - expect(curve.duration).toBe(0.2); - expect(curve.at(0)).toBe(0); - expect(curve.at(0.1)).toBeCloseTo(0.25, 6); - expect(curve.at(0.2)).toBe(1); - expect(curve.velocity(0.1)).toBeCloseTo(5, 3); - expect(curve.velocity(0.2)).toBe(0); - const none = easedProgress(0, x => x); - expect(none.at(0)).toBe(1); - expect(none.velocity(0)).toBe(0); - }); - - it('with jumps, a jump carries no speed and a smooth stretch keeps its slope', () => { - const steps = (x: number) => Math.floor(4 * x) / 4; - // Without the option, the jump at a quarter of 300 ms reads as a spike. - expect(easedProgress(0.3, steps).velocity(0.075)).toBeGreaterThan(100); - const jumping = easedProgress(0.3, steps, {jumps: true}); - for (const t of [0, 0.0749, 0.075, 0.0751, 0.15, 0.225, 0.2995]) { - expect(jumping.velocity(t), `${t} s`).toBe(0); - } - expect( - easedProgress(0.2, x => x * x, {jumps: true}).velocity(0.1), - ).toBeCloseTo(5, 1); - }); -}); diff --git a/packages/core/src/motion/themeTiming.ts b/packages/core/src/motion/themeTiming.ts index e7069f7da0138..ca5720e2f2879 100644 --- a/packages/core/src/motion/themeTiming.ts +++ b/packages/core/src/motion/themeTiming.ts @@ -8,8 +8,7 @@ * tokens where the element is. It plays an easing that is not a cubic * Bézier as the browser plays it. readThemeTokens and resolveTiming: that * duration and easing as values. readThemeTokenText: a token's text where - * the element is. easedProgress: the curve for a length and an easing - * already read. + * the element is. * @position Motion foundation, internal to core. Motion that a tap, a key or * the program starts reads its duration and easing from the theme with it. * @@ -19,6 +18,7 @@ import type {MotionCurve} from './animator'; import {cubicBezier} from './bezier'; +import {easedProgress} from './progress'; import {parseCssEasing, parseMotionRoleValue} from './roles'; import type {MotionCurvePoints} from './roleValue'; import {resolveTokenReferences} from '../theme/tokenReferences'; @@ -61,46 +61,6 @@ export interface ResolvedTiming { readonly points: MotionCurvePoints | null; } -/** - * The eased progress from 0 to 1 over `seconds`, as a MotionCurve whose - * velocity is in progress per second. A curve of no length is at its end. - * With `jumps`, a jump in the easing, as in `steps()`, carries no speed. The - * gentler of the slopes just before and just after counts. - */ -export function easedProgress( - seconds: number, - ease: (x: number) => number, - {jumps = false}: {readonly jumps?: boolean} = {}, -): MotionCurve { - const at = (t: number) => - seconds <= 0 || t >= seconds ? 1 : ease(Math.max(0, t) / seconds); - // A central difference, one step inside the curve at either end. - const step = Math.min(1e-3, seconds / 100); - return { - duration: seconds, - at, - velocity: t => { - if (seconds <= 0 || t >= seconds) { - return 0; - } - const before = Math.max(0, t - step); - const after = Math.min(seconds, t + step); - if (!jumps) { - return (at(after) - at(before)) / (after - before); - } - const here = at(t); - const slopes: number[] = []; - if (t > before) { - slopes.push((here - at(before)) / (t - before)); - } - if (after > t) { - slopes.push((at(after) - here) / (after - t)); - } - return slopes.reduce((a, b) => (Math.abs(b) < Math.abs(a) ? b : a)); - }, - }; -} - function firstDurationMs(style: CSSStyleDeclaration): number | null { return parseMotionRoleValue( 'duration', From ad7f8fbf2893e38d4b54a4db72cb7d65543053ea Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:24:05 -0800 Subject: [PATCH 13/65] test(motion): the popover's turn-around reads Popover's live curves The morph's turn-around proof compared restartFrom with lines written in the test, so a change to Popover's readState or surfaceCurves left it green. Popover exports both for the proofs, which now replay its own turn-around. morphPath.ts's header keeps only its tags: the paths' own JSDoc says the rest. --- .../core/src/Popover/popoverSurfaceMotion.ts | 17 +++++-- packages/core/src/motion/morphPath.test.ts | 49 ++++++++++++------- packages/core/src/motion/morphPath.ts | 16 ------ 3 files changed, 46 insertions(+), 36 deletions(-) diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.ts index fb3ff9f304a2a..df4a0757584fd 100644 --- a/packages/core/src/Popover/popoverSurfaceMotion.ts +++ b/packages/core/src/Popover/popoverSurfaceMotion.ts @@ -56,8 +56,11 @@ export type { /** * The curves from `from` to `to` as `progress` moves from 0 to 1. The scale * and the length move together, so the scale along the axis is their product. + * + * @internal Read by the rect morph's popover proofs; not exported from the + * package. */ -function surfaceCurves( +export function surfaceCurves( from: SurfaceState, to: SurfaceState, axis: 'x' | 'y', @@ -82,8 +85,16 @@ function timingOn(element: Element, tokens: ThemeTimingTokens): MotionCurve { return readThemeTiming(element, tokens) ?? easedProgress(0, x => x); } -/** What `animator` shows now, split back into scale and length. */ -function readState(animator: Animator, axis: 'x' | 'y'): SurfaceState { +/** + * What `animator` shows now, split back into scale and length. + * + * @internal Read by the rect morph's popover proofs; not exported from the + * package. + */ +export function readState( + animator: Pick, + axis: 'x' | 'y', +): SurfaceState { const across = animator.get(axis === 'x' ? 'scaleY' : 'scaleX'); const along = animator.get(axis === 'x' ? 'scaleX' : 'scaleY'); return { diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts index ba05771518861..f30278851c6f7 100644 --- a/packages/core/src/motion/morphPath.test.ts +++ b/packages/core/src/motion/morphPath.test.ts @@ -25,8 +25,10 @@ import { frameOf, popoverCollapsedState, popoverFrame, + PRESENTED, type PopoverCollapsedState, } from '../Popover/popoverSurfaceFrame'; +import {readState, surfaceCurves} from '../Popover/popoverSurfaceMotion'; import {progressCurve} from './progress'; const SPRING = {response: 0.4, dampingRatio: 1}; @@ -332,26 +334,39 @@ describe('the presentations that move onto the morph are the same rect at every height: 44, }); const path = popoverPath(surface, state); - const rectOf = (scale: number, length: number) => - popoverRect( - surface, - state, - frameOf({scale, length, opacity: 1}, state.axis), - ); - // Mid-dismissal: scale 0.4, length 0.6 (readState), opacity 0.5. - const onScreen = rectOf(0.4, 0.6); + // Mid-dismissal: scale 0.4, length 0.6, opacity 0.5 on screen. + const shown = frameOf({scale: 0.4, length: 0.6, opacity: 0.5}, state.axis); + const onScreen = popoverRect(surface, state, shown); + // Popover's own turn-around: it reads that frame back and plays on. + const from = readState( + {get: (property: string) => shown[property as keyof typeof shown]}, + state.axis, + ); + const linear: MotionCurve = {duration: 1, at: t => t, velocity: () => 1}; + const toRest = surfaceCurves(from, PRESENTED, state.axis, linear); + const toSource = surfaceCurves( + from, + {scale: state.scale, length: state.length, opacity: 0}, + state.axis, + linear, + ); 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]) { - // Popover's curves: each of scale, length and opacity on a line. - expectRect(back.rectAt(p), rectOf(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), - rectOf(0.4 + (state.scale - 0.4) * p, 0.6 + (state.length - 0.6) * p), - 0.5, - ); - expect(away.opacityAt!(p)).toBeCloseTo(0.5 - 0.5 * p, 9); + for (const [morph, live] of [ + [back, toRest], + [away, toSource], + ] as const) { + expectRect( + morph.rectAt(p), + popoverRect(surface, state, { + scaleX: live.scaleX.at(p), + scaleY: live.scaleY.at(p), + }), + 0.5, + ); + expect(morph.opacityAt!(p)).toBeCloseTo(live.opacity.at(p), 9); + } } }); diff --git a/packages/core/src/motion/morphPath.ts b/packages/core/src/motion/morphPath.ts index 622f2720b4215..a5c48e905b101 100644 --- a/packages/core/src/motion/morphPath.ts +++ b/packages/core/src/motion/morphPath.ts @@ -14,22 +14,6 @@ * 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 From 33a3ee89bf21f7c0aab04e44db5c13c6b01fbb17 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:52:45 -0800 Subject: [PATCH 14/65] docs(changeset): the rect morph's note names the eased-progress move The note said timedProgressCurve joins the progress helpers, which this pull request no longer adds. It now says easedProgress moves to them with a retargeted velocity, and timedCurve joins them. --- .changeset/motion-rect-morph.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/motion-rect-morph.md b/.changeset/motion-rect-morph.md index e7003e85f8e4b..b8bdc4c49e1a1 100644 --- a/.changeset/motion-rect-morph.md +++ b/.changeset/motion-rect-morph.md @@ -2,6 +2,6 @@ '@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. Each play takes the timing the component's motion record names (AST-094 FR45): a duration and easing, or a spring, starting from the velocity it is given. Reduced Motion is left to the animator. `timedProgressCurve` joins the progress helpers. Not exported from the package entry point; no component uses it yet. +[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. Each play takes the timing the component's motion record names (AST-094 FR45): a duration and easing, or a spring, starting from the velocity it is given. Reduced Motion is left to the animator. `easedProgress` moves to the progress helpers and keeps a retargeted velocity; `timedCurve` joins them. Not exported from the package entry point; no component uses it yet. @vjeux From 822013a38081dacb5ec9d9b70259949957678933 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 23:55:36 -0800 Subject: [PATCH 15/65] test(motion): the popover's turn-around compares opacity as drawn Popover's surface curves now stop their opacity at 0 or a floor above it. Past its end, a turn-around toward the source takes the popover path's opacity below 0, where Popover's stops at 0. An opacity draws clamped to 0 through 1, so both draw 0. The proof now compares the two as drawn, which holds with Popover's curves before and after the floor. --- packages/core/src/motion/morphPath.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts index f30278851c6f7..7e7e1e68ba7b8 100644 --- a/packages/core/src/motion/morphPath.test.ts +++ b/packages/core/src/motion/morphPath.test.ts @@ -352,6 +352,10 @@ describe('the presentations that move onto the morph are the same rect at every ); const back = path.restartFrom!(onScreen, 0.5, 'rest'); const away = path.restartFrom!(onScreen, 0.5, 'source'); + // An opacity draws clamped to 0 through 1. Past its end, a turn-around + // toward the source takes the path below 0, where Popover's curves stop + // at 0. Both draw 0, so the proof compares them as drawn. + const drawn = (opacity: number) => Math.min(1, Math.max(0, opacity)); for (const p of [0, 0.25, 0.5, 0.75, 1, 1.05]) { for (const [morph, live] of [ [back, toRest], @@ -365,7 +369,10 @@ describe('the presentations that move onto the morph are the same rect at every }), 0.5, ); - expect(morph.opacityAt!(p)).toBeCloseTo(live.opacity.at(p), 9); + expect(drawn(morph.opacityAt!(p))).toBeCloseTo( + drawn(live.opacity.at(p)), + 9, + ); } } }); From 6354fa3fe4dcdc57b324eb93ca02aaa3276f56b3 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 9 Nov 2026 19:55:25 -0800 Subject: [PATCH 16/65] fix(motion): a popover's morph never reads an opacity below 0 A popover's grow path read its opacity on a straight line, so before its start and past its end it went below 0: a turn-around toward the source read -0.025 at 1.05. An opacity below 0 draws as 0, so opacityAt now stops at 0. The popover proofs compare opacities as drawn, since Popover's own model still reads below 0 there. --- packages/core/src/motion/morphPath.test.ts | 35 ++++++++++++++++++---- packages/core/src/motion/morphPath.ts | 4 ++- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts index 7e7e1e68ba7b8..01b2392147cd5 100644 --- a/packages/core/src/motion/morphPath.test.ts +++ b/packages/core/src/motion/morphPath.test.ts @@ -285,6 +285,12 @@ function cardModel(box: MorphRect) { /** 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); +/** + * An opacity as drawn: clamped to 0 through 1. A popover's path stops at 0, + * while Popover's own model reads below 0 before its start and past its end. + */ +const drawn = (opacity: number) => Math.min(1, Math.max(0, opacity)); + 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}; @@ -320,7 +326,7 @@ describe('the presentations that move onto the morph are the same rect at every for (const p of PROGRESSES) { const frame = popoverFrame(state, p); expectRect(path.rectAt(p), popoverRect(surface, state, frame), 0.5); - expect(path.opacityAt!(p)).toBeCloseTo(frame.opacity, 9); + expect(path.opacityAt!(p)).toBeCloseTo(Math.max(0, frame.opacity), 9); } } }); @@ -352,10 +358,6 @@ describe('the presentations that move onto the morph are the same rect at every ); const back = path.restartFrom!(onScreen, 0.5, 'rest'); const away = path.restartFrom!(onScreen, 0.5, 'source'); - // An opacity draws clamped to 0 through 1. Past its end, a turn-around - // toward the source takes the path below 0, where Popover's curves stop - // at 0. Both draw 0, so the proof compares them as drawn. - const drawn = (opacity: number) => Math.min(1, Math.max(0, opacity)); for (const p of [0, 0.25, 0.5, 0.75, 1, 1.05]) { for (const [morph, live] of [ [back, toRest], @@ -377,6 +379,29 @@ describe('the presentations that move onto the morph are the same rect at every } }); + it('a popover never reads an opacity below 0, before its start or past its end', () => { + const surface = {x: 41, y: 204, width: 320, height: 253}; + const state = popoverState(surface, { + x: 141, + y: 160, + width: 120, + height: 44, + }); + const path = popoverPath(surface, state); + const shown = frameOf({scale: 0.4, length: 0.6, opacity: 0.5}, state.axis); + const away = path.restartFrom!( + popoverRect(surface, state, shown), + 0.5, + 'source', + ); + for (const p of [-0.1, -0.05, 0]) { + expect(path.opacityAt!(p)).toBe(0); + } + for (const p of [1, 1.05, 1.1]) { + expect(away.opacityAt!(p)).toBe(0); + } + }); + 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; diff --git a/packages/core/src/motion/morphPath.ts b/packages/core/src/motion/morphPath.ts index a5c48e905b101..0a528093c3c46 100644 --- a/packages/core/src/motion/morphPath.ts +++ b/packages/core/src/motion/morphPath.ts @@ -143,7 +143,9 @@ function growPath( height: box.height * scaleY, }; }, - opacityAt: p => stateAt(p).opacity, + // Before its start and past its end, the straight line reads below 0, + // which draws as 0. + opacityAt: p => Math.max(0, 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; From 6b6310c69c75a1158982b8114eef1e528eb6d912 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 9 Nov 2026 21:52:52 -0800 Subject: [PATCH 17/65] test(motion): the morph proofs drop the menu's old straight line The anchored menu's case modeled a straight line from a 22 px square on its control. The menu now grows out of its trigger on Popover's edge path, which the popover cases already check, so the case no longer describes any presentation's model. The file header follows. --- packages/core/src/motion/morphPath.test.ts | 41 ++-------------------- 1 file changed, 3 insertions(+), 38 deletions(-) diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts index 01b2392147cd5..0d996173a2da4 100644 --- a/packages/core/src/motion/morphPath.test.ts +++ b/packages/core/src/motion/morphPath.test.ts @@ -6,9 +6,9 @@ * 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 + * every frame. Checks that each presentation's model (popover, lifted + * preview, zoom, sub-menu parent card) is the same rect at every progress, + * within 0.5 px * @position Testing; the rect morph's player has its own tests */ @@ -193,27 +193,6 @@ function popoverPath(surface: MorphRect, state: PopoverCollapsedState) { }); } -/** 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 = { @@ -292,20 +271,6 @@ const PROGRESSES = Array.from({length: 24}, (_, i) => -0.05 + i * 0.05); const drawn = (opacity: number) => Math.min(1, Math.max(0, opacity)); 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 = { From 9d6c0a2f7a5117f786a0a312042e84a886d6ad45 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 25 Oct 2026 19:38:32 -0700 Subject: [PATCH 18/65] feat(lift): one opt-in lift-from-trigger presentation An internal module, separate from Layer, for the presentation that lifts a trigger out of the page above a tinted backdrop, grows a surface (a menu) out of the press beside it, shrinks the surface back into the press and returns the trigger to its place. Only a surface that opts in uses it; Layer keeps the top layer, dismissal, the presentation hold and the shared exit copy, which the lift uses. - The trigger itself lifts, as a manual popover in the top layer laid out at its own size where it stood, with one empty placeholder after it holding its spot: no clipping or stacking ancestor cuts it, the page does not move, and the trigger keeps its look and its place among its siblings. While lifted the page has four elements more whatever the trigger holds (the layer, whose ::backdrop is the tint; the shadow; an empty box at the lifted rect for the surface to be placed against, since anchor positioning follows transforms; the placeholder), five with the hold's shield, and none at rest (spec:AST-017 FR60, DEC-29). - Every motion is translate, scale or opacity on the compositor (spec:AST-094 FR5): the trigger and the surface on the shared rect morph, which continues an interrupted motion with its velocity (FR6); the shadow follows the trigger frame for frame as one sampled animation (the same start, path and spring, and on the way back the rect and velocity the trigger's morph reads at the same instant) and fades on its own spring; the tint is a spring-sampled opacity animation of the layer's ::backdrop, which clears from what it shows. (Animating a ::backdrop of the trigger itself restyled and laid out the page on every frame.) - It reads the page before it writes to it: the trigger's box, its look, the theme's springs, and the tint, the shadow and the layer runtime's gutter resolved on an undisplayed probe. A caller's `release` (a press feedback letting go of the trigger) runs between the reads and the writes, and the hold's shield shows before a surface's growth writes, so the page restyles once for each. - A tap while the trigger and the surface grow reaches nothing (FR35); the close holds the layer until the trigger is back, the surface's exit copy has shrunk and every press on the layer has lifted; its timers and document listeners end with it, and an unmount ends everything at once (FR24). - The springs, scale rule and gap are the caller's motion roles and constants; the geometry (liftGeometry.ts) is generic. Tests: jsdom (what a lift adds and puts back, no element, listener or timer left after a drop, an unmount or twenty lifts, the gutter it resolves, the holds, backdrop taps) and Chromium and WebKit on an esbuild fixture (the top layer and the placeholder, the shadow under the trigger on every frame of the lift and the drop, the tint clearing from what it shows, the properties that move, the surface's growth, fade-in and exit copy, the element counts, no node or listener leak over ten lifts, a tap during the growth). --- .changeset/lift-module.md | 7 + packages/core/src/lift/README.md | 54 + .../core/src/lift/__tests__/lift.fixture.ts | 129 ++ .../lift.interaction.browser.spec.ts | 512 +++++++ packages/core/src/lift/lift.test.ts | 406 ++++++ packages/core/src/lift/lift.ts | 1270 +++++++++++++++++ packages/core/src/lift/liftGeometry.test.ts | 103 ++ packages/core/src/lift/liftGeometry.ts | 149 ++ packages/core/src/lift/useLift.ts | 30 + 9 files changed, 2660 insertions(+) create mode 100644 .changeset/lift-module.md create mode 100644 packages/core/src/lift/README.md create mode 100644 packages/core/src/lift/__tests__/lift.fixture.ts create mode 100644 packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts create mode 100644 packages/core/src/lift/lift.test.ts create mode 100644 packages/core/src/lift/lift.ts create mode 100644 packages/core/src/lift/liftGeometry.test.ts create mode 100644 packages/core/src/lift/liftGeometry.ts create mode 100644 packages/core/src/lift/useLift.ts diff --git a/.changeset/lift-module.md b/.changeset/lift-module.md new file mode 100644 index 0000000000000..b0d245df28b34 --- /dev/null +++ b/.changeset/lift-module.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, four elements while lifted. Not exported from the package entry point; no component uses it yet. + +@vjeux diff --git a/packages/core/src/lift/README.md b/packages/core/src/lift/README.md new file mode 100644 index 0000000000000..918fdb53f7aa6 --- /dev/null +++ b/packages/core/src/lift/README.md @@ -0,0 +1,54 @@ +# Lift + +The one lift-from-trigger presentation, internal to core and opt-in. A +surface that chooses it (ContextMenu's touch invocation today) lifts its +trigger out of the page above a tinted backdrop, grows a surface (a menu) out +of the press beside it, shrinks that surface back into the press when it +closes, and returns the trigger to its place. Nothing else gets it by +default, and any surface that lifts uses this module, never a copy of it. +Nothing here is exported from the package entry point; components import it +by path. + +Layer stays generic. The top layer, dismissal, the presentation hold +(`Layer/presentationHold.ts`) and the shared exit copy +(`Layer/layerExitCopy.ts`) belong to Layer; the lift only uses them. Its +motion is the rect morph's (`motion/rectMorph.ts`), and its springs, scale +rule and gap are the caller's own motion roles and constants, so a theme +retunes them where the surface declares them. + +## What a lift adds + +The trigger itself lifts, not a copy: it becomes a manual popover in the top +layer, laid out at its own size where it stood, so no clipping, transformed +or stacking ancestor cuts or covers it, and an empty placeholder after it +holds its spot, so the page does not move. While lifted the page has four +elements more, whatever the trigger holds: the lift layer (its `::backdrop` +is the tint); the shadow, a box in the layer that follows the trigger on a +rect morph of its own (an animated `::backdrop` of the trigger would restyle +and lay out the page on every frame); an empty box at the lifted rect for +the surface to be placed against (anchor positioning follows transforms, so +a box inside the trigger would move with it); and the placeholder. The presentation hold's shield joins while the lift grows and +while it closes: never more than five (`spec:AST-017` FR60, DEC-29). The +exit copy the surface shrinks on is the layer runtime's transient copy. At +rest there is nothing. + +## Motion + +Every motion is `translate`, `scale` or `opacity` on the compositor +(`spec:AST-094` FR5): the trigger, its shadow and the surface on the rect morph, +which continues an interrupted motion with the velocity on screen (FR6); the +tint as a spring-sampled Web Animation of the layer's `::backdrop`. A +tap or a drag that lands while the lift and the surface grow reaches nothing +(FR35). The close holds the layer until the trigger is back, the surface's +exit is done and every press on the layer has lifted. Its timers and +document listeners end with it, and an unmount ends everything at once +(FR24). Reduce Motion is the animator's (`design:reduced-motion`). + +## Files + +| File | What it is | +| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `lift.ts` | `createLift`: lift a trigger, grow and close a surface beside it, drop, end. | +| `useLift.ts` | A component's one lift, ended when it unmounts. | +| `liftGeometry.ts` | How far the trigger grows, where it lands inside the layer runtime's gutter, which side the surface takes. | +| `__tests__/lift.interaction.browser.spec.ts` | Browser proofs (Chromium and WebKit): the top layer, the placeholder, the properties that move, counts, leaks. | diff --git a/packages/core/src/lift/__tests__/lift.fixture.ts b/packages/core/src/lift/__tests__/lift.fixture.ts new file mode 100644 index 0000000000000..17465ff30ac50 --- /dev/null +++ b/packages/core/src/lift/__tests__/lift.fixture.ts @@ -0,0 +1,129 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file lift.fixture.ts + * @input Nothing: bundled by esbuild and injected into a blank page + * @output A page with a list of rows inside a clipping, transformed panel + * (the first row rounded by `:first-child`, the second holding twelve + * elements), a menu popover beside it, and `window.__lift`: lift a row, + * grow and close the menu, drop, end, and the backdrop taps and the + * clicks the page received + * @position Browser fixture of lift.interaction.browser.spec.ts; test-only + */ + +import {createLift, type LiftOptions, type LiftResult} from '../lift'; + +interface LiftLog { + backdropTaps: number; + clicks: string[]; +} + +/** The page's handle on its lift. */ +export interface LiftFixture { + log: LiftLog; + lift: (id: string, springResponse?: number) => LiftResult | null; + presentMenu: (press: {x: number; y: number} | null) => void; + dismissMenu: () => void; + closeMenu: () => void; + showMenu: () => void; + drop: () => void; + dispose: () => void; + isLifted: () => boolean; +} + +declare global { + interface Window { + __lift: LiftFixture; + } +} + +document.documentElement.style.cssText = + '--color-overlay: rgba(1, 18, 40, 0.4); --shadow-high: 0 8px 24px rgba(0, 0, 0, 0.3); --spacing-4: 16px;'; +document.body.style.margin = '0'; +document.body.style.font = '16px sans-serif'; +const deep = Array.from( + {length: 3}, + (_, i) => + `
${i * 3 + 1}${i * 3 + 2}${i * 3 + 3}
`, +).join(''); +document.body.innerHTML = ` + +
+
    +
  • Row 1
  • +
  • ${deep}
  • +
  • Row 3
  • +
  • Row 4
  • +
+
+ + `; + +function element(id: string): HTMLElement { + const found = document.getElementById(id); + if (found == null) { + throw new Error(`missing #${id}`); + } + return found; +} + +const log: LiftLog = {backdropTaps: 0, clicks: []}; +document.addEventListener( + 'click', + event => { + const target = event.target; + if (target instanceof Element) { + log.clicks.push(target.id || target.tagName.toLowerCase()); + } + }, + true, +); + +const lift = createLift(); + +function options(response: number): LiftOptions { + const spring = {response, dampingRatio: 0.9}; + return { + motion: { + lift: spring, + drop: spring, + clear: spring, + shadowIn: spring, + shadowOut: spring, + surfaceIn: spring, + surfaceOut: spring, + }, + scale: {maxScale: 1.15, scaleUpPoints: 26}, + surfaceStartWidth: 44, + attribute: 'data-lift', + onBackdropTap: () => { + log.backdropTaps += 1; + }, + }; +} + +window.__lift = { + log, + lift: (id, springResponse = 0.3) => + lift.lift(element(id), options(springResponse)), + showMenu: () => element('menu').showPopover(), + presentMenu: press => { + element('menu').showPopover(); + lift.presentSurface( + element('menu').querySelector('[role="menu"]') ?? + element('menu'), + press, + ); + }, + dismissMenu: () => lift.dismissSurface(element('menu')), + closeMenu: () => element('menu').hidePopover(), + drop: () => lift.drop(), + dispose: () => lift.dispose(), + isLifted: () => lift.isLifted(), +}; diff --git a/packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts b/packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts new file mode 100644 index 0000000000000..2281de2382e27 --- /dev/null +++ b/packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts @@ -0,0 +1,512 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file lift.interaction.browser.spec.ts + * @input The lift bundled with esbuild onto a blank fixture page + * (lift.fixture.ts): a list of rows in a clipping, transformed panel and a + * menu popover; Chromium and WebKit + * @output Proof in real engines that a row lifts itself into the top layer + * at its lifted rect while one placeholder holds its spot (nothing else + * moves, and the row keeps its look); that every motion the lift plays is + * `translate`, `scale`, `transform` or `opacity` (spec:AST-094 FR5); that + * the menu grows out of the press and keeps nothing inline at rest, and + * its close shrinks the layer runtime's exit copy back into it, or, with + * no press, fades in where it rests; that the + * page has the layer, the shadow, the anchor and the placeholder more while + * lifted, whatever the row holds, at most 5 at any moment, and none after + * the drop + * (AST-017 FR60); that repeated lifts leave no node or listener behind; + * that a tap while it grows reaches nothing (FR35) and one on the backdrop + * afterwards is the backdrop tap + * @position Browser proof for lift.ts, run by `pnpm test:interaction`; jsdom + * has no layout, no top layer and no animations + */ + +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {expect, test, type Page} from '@playwright/test'; +import {build, type Plugin} from 'esbuild'; +// The page's `window.__lift`. +import type {LiftFixture} from './lift.fixture'; + +// The layer runtime's gutter is a `stylex.defineConsts` table: static values +// the StyleX compiler puts in place of the call. Unbundled by that compiler, +// the call returns its values here. +const stylexConsts: Plugin = { + name: 'stylex-consts', + setup(builder) { + // esbuild's filters are Go regular expressions, which take no flags. + builder.onResolve({filter: /^@stylexjs\/stylex$/}, () => ({ + path: 'stylex-consts', + namespace: 'stylex-consts', + })); + builder.onLoad({filter: /.*/, namespace: 'stylex-consts'}, () => ({ + contents: 'export const defineConsts = consts => consts;', + loader: 'js', + })); + }, +}; + +let bundle = ''; + +test.beforeAll(async () => { + const result = await build({ + entryPoints: [ + path.join( + path.dirname(fileURLToPath(import.meta.url)), + 'lift.fixture.ts', + ), + ], + bundle: true, + write: false, + format: 'iife', + platform: 'browser', + target: 'es2022', + plugins: [stylexConsts], + }); + bundle = result.outputFiles[0].text; +}); + +// A real navigation (not setContent): the page keeps its own window. +async function open(page: Page) { + const html = ``; + await page.route('http://lift.test/', async route => + route.fulfill({contentType: 'text/html', body: html}), + ); + await page.goto('http://lift.test/'); +} + +type Box = [number, number, number, number]; +type LiftResult = NonNullable>; + +function expectBox(actual: Box, expected: Box, tolerance = 0.5) { + for (let i = 0; i < 4; i++) { + expect(Math.abs(actual[i] - expected[i])).toBeLessThanOrEqual(tolerance); + } +} + +test('a row lifts itself into the top layer at its lifted rect while one placeholder holds its spot: nothing else moves, and the row keeps its look', async ({ + page, +}) => { + await open(page); + const read = async () => + page.evaluate(() => { + const box = (element: Element | null): Box => { + const r = element?.getBoundingClientRect(); + return r == null ? [0, 0, 0, 0] : [r.x, r.y, r.width, r.height]; + }; + const row = document.getElementById('row2') as HTMLElement; + const style = getComputedStyle(row); + return { + row1: box(document.getElementById('row1')), + row2: box(row), + row3: box(document.getElementById('row3')), + row4: box(document.getElementById('row4')), + placeholder: box(document.querySelector('[data-lift-placeholder]')), + shadow: box(document.querySelector('[data-lift-shadow]')), + isOpen: row.matches(':popover-open'), + look: [ + style.color, + style.backgroundColor, + style.borderBottomWidth, + style.borderBottomColor, + style.paddingLeft, + style.fontSize, + style.display, + ], + }; + }); + const before = await read(); + const result = await page.evaluate(() => window.__lift.lift('row2', 0.2)); + expect(result).not.toBeNull(); + await page.waitForTimeout(800); + const after = await read(); + expect(after.isOpen).toBe(true); + // Grown by 26 px on its larger side, about its center: wider than the + // clipping panel, and drawn whole. + const lifted: LiftResult['lifted'] = result?.lifted ?? { + x: 0, + y: 0, + width: 0, + height: 0, + }; + expect(lifted.width).toBeCloseTo(361, 3); + expectBox(after.row2, [lifted.x, lifted.y, lifted.width, lifted.height]); + // Its shadow lies exactly under it. + expectBox(after.shadow, [lifted.x, lifted.y, lifted.width, lifted.height]); + expectBox(after.placeholder, before.row2); + expectBox(after.row1, before.row1); + expectBox(after.row3, before.row3); + expectBox(after.row4, before.row4); + expect(after.look).toEqual(before.look); + await page.evaluate(() => window.__lift.dispose()); +}); + +test('the shadow follows the row on every frame of its lift and of its drop', async ({ + page, +}) => { + await open(page); + // Every animation of the lift, held at the same moment `t` ms in. + const at = async (t: number) => + page.evaluate(time => { + for (const animation of document.getAnimations()) { + animation.pause(); + animation.currentTime = time; + } + const box = (element: Element | null): Box => { + const r = element?.getBoundingClientRect(); + return r == null ? [0, 0, 0, 0] : [r.x, r.y, r.width, r.height]; + }; + return { + row: box(document.getElementById('row2')), + shadow: box(document.querySelector('[data-lift-shadow]')), + }; + }, t); + await page.evaluate(() => window.__lift.lift('row2', 0.2)); + await page.waitForTimeout(50); + for (const t of [30, 90, 180]) { + const {row, shadow} = await at(t); + expectBox(shadow, row); + } + await page.evaluate(() => { + for (const animation of document.getAnimations()) { + animation.finish(); + } + window.__lift.drop(); + }); + await page.waitForTimeout(50); + for (const t of [30, 90]) { + const {row, shadow} = await at(t); + expectBox(shadow, row); + } + await page.evaluate(() => window.__lift.dispose()); +}); + +test('the tint clears from what it shows when the row drops, with no jump to clear', async ({ + page, +}) => { + await open(page); + await page.evaluate(() => window.__lift.lift('row2', 0.2)); + await page.waitForTimeout(600); + const tint = await page.evaluate(() => { + const layer = document.querySelector('[data-lift]'); + // The opacity keyframes of the tint animations on the layer's + // `::backdrop` (the layer itself animates nothing), oldest first. + // WebKit reports no `pseudoElement` on the effect. + const fades = () => + (layer?.getAnimations({subtree: true}) ?? []) + .filter(animation => { + const effect = animation.effect as KeyframeEffect | null; + return ( + effect?.target === layer && + animation.playState !== 'idle' && + effect.getKeyframes().some(frame => 'opacity' in frame) && + new Set(effect.getKeyframes().map(frame => frame.opacity)).size > 1 + ); + }) + .map(animation => + (animation.effect as KeyframeEffect) + .getKeyframes() + .map(frame => Number(frame.opacity)), + ); + const shown = fades().at(-1)?.at(-1) ?? -1; + window.__lift.drop(); + const clear = fades().at(-1) ?? []; + return {shown, from: clear[0] ?? -1, to: clear.at(-1) ?? -1}; + }); + const detail = JSON.stringify(tint); + // Risen, the tint clears from there to nothing. + expect(tint.shown, detail).toBeCloseTo(1, 2); + expect(tint.from, detail).toBeGreaterThan(0.95); + expect(tint.to, detail).toBeCloseTo(0, 2); + await page.evaluate(() => window.__lift.dispose()); +}); + +test('every motion the lift plays, the menu’s growth and close included, is translate, scale, transform or opacity (spec:AST-094 FR5)', async ({ + page, +}) => { + await open(page); + const properties = await page.evaluate(async () => { + const seen = new Set(); + const ignored = new Set([ + 'offset', + 'computedOffset', + 'easing', + 'composite', + ]); + const collect = () => { + for (const animation of document.getAnimations()) { + const effect = animation.effect as KeyframeEffect | null; + // A zero-length fill holds a value; it plays no motion. + if (effect == null || effect.getComputedTiming().duration === 0) { + continue; + } + for (const keyframe of effect.getKeyframes()) { + for (const property of Object.keys(keyframe)) { + if (!ignored.has(property)) { + seen.add(property); + } + } + } + } + }; + const frame = async () => + new Promise(resolve => requestAnimationFrame(resolve)); + window.__lift.lift('row2', 0.4); + window.__lift.presentMenu({x: 180, y: 330}); + collect(); + await frame(); + await frame(); + collect(); + window.__lift.dismissMenu(); + window.__lift.closeMenu(); + window.__lift.drop(); + collect(); + await frame(); + await frame(); + collect(); + return [...seen].sort(); + }); + expect(properties.length).toBeGreaterThan(0); + expect( + properties.filter( + property => + !['opacity', 'scale', 'transform', 'translate'].includes(property), + ), + ).toEqual([]); +}); + +test('the menu grows out of the press into its box and keeps nothing inline at rest; its close shrinks the exit copy back into the press', async ({ + page, +}) => { + await open(page); + await page.evaluate(() => window.__lift.lift('row2', 0.3)); + await page.waitForTimeout(600); + const press = {x: 180, y: 330}; + const early = await page.evaluate(async at => { + window.__lift.presentMenu(at); + await new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + const r = ( + document.getElementById('menu') as HTMLElement + ).getBoundingClientRect(); + return {x: r.x + r.width / 2, y: r.y + r.height / 2, width: r.width}; + }, press); + // Small, and nearer the press than its own center. + expect(early.width).toBeLessThan(125); + const fromPress = Math.hypot(early.x - press.x, early.y - press.y); + const fromBox = Math.hypot(early.x - 165, early.y - 510); + expect(fromPress).toBeLessThan(fromBox); + await page.waitForTimeout(900); + const rest = await page.evaluate(() => { + const menu = document.getElementById('menu') as HTMLElement; + const r = menu.getBoundingClientRect(); + return { + box: [r.x, r.y, r.width, r.height] as Box, + translate: menu.style.translate, + scale: menu.style.scale, + opacity: getComputedStyle(menu).opacity, + }; + }); + expectBox(rest.box, [40, 420, 250, 180]); + expect(rest.translate).toBe(''); + expect(rest.scale).toBe(''); + expect(rest.opacity).toBe('1'); + const copy = await page.evaluate(async () => { + window.__lift.dismissMenu(); + window.__lift.closeMenu(); + const placed = document.querySelector('[data-lift-exit]'); + if (placed == null) { + return null; + } + // Its narrowest over the next frames: it starts as the menu stands. + let width = Infinity; + for (let i = 0; i < 20 && width >= 250; i++) { + await new Promise(resolve => requestAnimationFrame(resolve)); + width = Math.min(width, placed.getBoundingClientRect().width); + } + return { + isOpen: placed.matches(':popover-open'), + inert: placed.inert, + hidden: placed.getAttribute('aria-hidden'), + width, + }; + }); + expect(copy).not.toBeNull(); + expect(copy?.isOpen).toBe(true); + expect(copy?.inert).toBe(true); + expect(copy?.hidden).toBe('true'); + // Shrinking already. + expect(copy?.width ?? 0).toBeLessThan(250); + await page.waitForTimeout(900); + expect( + await page.evaluate(() => document.querySelector('[data-lift-exit]')), + ).toBeNull(); + await page.evaluate(() => window.__lift.dispose()); +}); + +test('without a press the menu fades in where it rests: opacity only, no travel or growth', async ({ + page, +}) => { + await open(page); + await page.evaluate(() => window.__lift.lift('row2', 0.3)); + await page.waitForTimeout(600); + const early = await page.evaluate(async () => { + window.__lift.presentMenu(null); + await new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + const menu = document.getElementById('menu') as HTMLElement; + const r = menu.getBoundingClientRect(); + const moving = new Set(); + for (const animation of menu.getAnimations()) { + const effect = animation.effect as KeyframeEffect | null; + const frames = effect?.getKeyframes() ?? []; + for (const property of ['translate', 'scale', 'transform', 'opacity']) { + const values = new Set(frames.map(frame => String(frame[property]))); + if (values.size > 1) { + moving.add(property); + } + } + } + return { + box: [r.x, r.y, r.width, r.height] as Box, + opacity: Number(getComputedStyle(menu).opacity), + moving: [...moving].sort(), + }; + }); + expectBox(early.box, [40, 420, 250, 180]); + expect(early.opacity).toBeLessThan(1); + expect(early.moving).toEqual(['opacity']); + await page.waitForTimeout(900); + expect( + await page.evaluate( + () => + getComputedStyle(document.getElementById('menu') as HTMLElement) + .opacity, + ), + ).toBe('1'); + await page.evaluate(() => window.__lift.dispose()); +}); + +test('while lifted the page has the layer, the shadow, the anchor and the placeholder more, whatever the row holds, and never more than 5 (AST-017 FR60); a drop leaves the page as it was', async ({ + page, +}) => { + await open(page); + const counts = await page.evaluate(async () => { + // The layer runtime's exit copy is the transient copy INV7 allows (made + // by the layer runtime, gone within a second): not one of the lift's. + const count = () => + [...document.body.querySelectorAll('*')].filter( + element => element.closest('[data-lift-exit]') == null, + ).length; + const wait = async (ms: number) => + new Promise(resolve => setTimeout(resolve, ms)); + const row = document.getElementById('row2') as HTMLElement; + // As serialized: the same declarations, in the same order. + const style = row.style.cssText; + const rest = count(); + let most = 0; + let sampling = true; + const sample = () => { + most = Math.max(most, count() - rest); + if (sampling) { + requestAnimationFrame(sample); + } + }; + window.__lift.lift('row2', 0.3); + const deep = count() - rest; + requestAnimationFrame(sample); + window.__lift.presentMenu({x: 180, y: 330}); + await wait(700); + const open = count() - rest; + window.__lift.dismissMenu(); + window.__lift.closeMenu(); + window.__lift.drop(); + await wait(1200); + sampling = false; + const after = count() - rest; + const styleAfter = row.style.cssText; + const popoverAfter = row.getAttribute('popover'); + window.__lift.lift('row1', 0.3); + const shallow = count() - rest; + window.__lift.dispose(); + return { + deep, + open, + most, + after, + shallow, + style, + styleAfter, + popoverAfter, + lifted: window.__lift.isLifted(), + }; + }); + // A row of 13 elements and a row of 1: the same 4 more once grown (the + // layer, the shadow, the anchor and the placeholder), and the hold's + // shield while the lift grows. + expect(counts.deep).toBe(5); + expect(counts.shallow).toBe(5); + expect(counts.open).toBe(4); + expect(counts.most).toBeLessThanOrEqual(5); + expect(counts.after).toBe(0); + expect(counts.styleAfter).toBe(counts.style); + expect(counts.popoverAfter).toBeNull(); + expect(counts.lifted).toBe(false); +}); + +test('ten lifts and drops leave the DOM node and event listener counts where they were (no leaks)', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'DOM counters are a Chromium protocol'); + await open(page); + const cdp = await page.context().newCDPSession(page); + const counters = async () => { + await cdp.send('HeapProfiler.collectGarbage'); + return cdp.send('Memory.getDOMCounters'); + }; + const cycle = async () => + page.evaluate(async () => { + const wait = async (ms: number) => + new Promise(resolve => setTimeout(resolve, ms)); + window.__lift.lift('row2', 0.15); + window.__lift.presentMenu({x: 180, y: 330}); + await wait(400); + window.__lift.dismissMenu(); + window.__lift.closeMenu(); + window.__lift.drop(); + await wait(700); + }); + // One lift first: what a first lift sets up once (the hold's touch gate). + await cycle(); + const before = await counters(); + for (let i = 0; i < 10; i++) { + await cycle(); + } + const after = await counters(); + expect(after.jsEventListeners).toBe(before.jsEventListeners); + expect(after.nodes).toBeLessThanOrEqual(before.nodes); +}); + +test('a tap while the row and the menu grow reaches nothing; one on the backdrop once they settle is the backdrop tap, and reaches nothing under it either', async ({ + page, +}) => { + await open(page); + await page.evaluate(() => { + window.__lift.lift('row2', 0.8); + window.__lift.presentMenu({x: 180, y: 330}); + }); + await page.mouse.click(180, 700); + const growing = await page.evaluate(() => ({...window.__lift.log})); + expect(growing.backdropTaps).toBe(0); + expect(growing.clicks).not.toContain('page'); + await page.waitForTimeout(2000); + await page.mouse.click(180, 700); + const settled = await page.evaluate(() => ({...window.__lift.log})); + expect(settled.backdropTaps).toBe(1); + expect(settled.clicks).not.toContain('page'); + await page.evaluate(() => window.__lift.dispose()); +}); diff --git a/packages/core/src/lift/lift.test.ts b/packages/core/src/lift/lift.test.ts new file mode 100644 index 0000000000000..c31cca90e253b --- /dev/null +++ b/packages/core/src/lift/lift.test.ts @@ -0,0 +1,406 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file lift.test.ts + * @input vitest (jsdom), the lift, stand-ins for the popover API and for + * layout (jsdom has neither) and a spy on the presentation hold + * @output Checks the lift's bookkeeping in the page: while up it adds the + * layer and one placeholder whatever the source holds, and nothing at + * rest; the source keeps its place among its siblings; a drop or an + * unmount puts back exactly what the source had inline and takes the rest + * away; nothing of it (an element, a document listener, a timer) outlives + * it over repeated lifts; the gutter it reads; the holds it takes; taps on + * its backdrop + * @position Testing; the motion, the top layer and the counts in real + * engines are proven in __tests__/lift.interaction.browser.spec.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import * as presentationHold from '../Layer/presentationHold'; +import {createLift, type LiftOptions} from './lift'; + +vi.mock('../Layer/presentationHold', async importOriginal => ({ + ...(await importOriginal()), + holdPresentation: vi.fn(() => () => {}), +})); + +const {holdPresentation} = presentationHold; + +const SPRING = {response: 0.3, dampingRatio: 1}; + +function options(overrides: Partial = {}): LiftOptions { + return { + motion: { + lift: SPRING, + drop: SPRING, + clear: SPRING, + shadowIn: SPRING, + shadowOut: SPRING, + surfaceIn: SPRING, + surfaceOut: SPRING, + }, + scale: {maxScale: 1.15, scaleUpPoints: 26}, + surfaceStartWidth: 44, + attribute: 'data-test-lift', + ...overrides, + }; +} + +function place( + element: HTMLElement, + x: number, + y: number, + w: number, + h: number, +) { + element.getBoundingClientRect = () => + DOMRect.fromRect({x, y, width: w, height: h}); + Object.defineProperty(element, 'offsetWidth', {value: w, configurable: true}); + Object.defineProperty(element, 'offsetHeight', { + value: h, + configurable: true, + }); +} + +/** A list of three rows; the middle one, the source, holds 12 elements. */ +function renderList(): {source: HTMLElement; before: HTMLElement} { + document.body.innerHTML = ` +
    +
  • Before
  • +
  • +
    123
    +
    456
    +
    789
    +
  • +
  • After
  • +
`; + const source = document.getElementById('source') as HTMLElement; + place(source, 20, 300, 335, 60); + return { + source, + before: document.getElementById('before') as HTMLElement, + }; +} + +const count = () => document.body.querySelectorAll('*').length; + +/** + * The source's inline style is what it was: its own values, and none of the + * lift's. (Property by property: jsdom's style object keeps a `margin` + * shorthand of its own making once all four margins were set, which a + * browser does not.) + */ +function expectInlineAsBefore(source: HTMLElement) { + const lifted = [ + 'position', + 'left', + 'top', + 'right', + 'bottom', + 'height', + 'min-width', + 'min-height', + 'max-width', + 'max-height', + 'box-sizing', + 'pointer-events', + 'transition', + 'padding-top', + 'border-top-width', + 'background-color', + 'overflow-x', + 'translate', + 'scale', + 'transform-origin', + ]; + expect({ + color: source.style.getPropertyValue('color'), + width: source.style.getPropertyValue('width'), + ...Object.fromEntries( + lifted.map(property => [ + property, + source.style.getPropertyValue(property), + ]), + ), + }).toEqual({ + color: 'red', + width: '50%', + ...Object.fromEntries(lifted.map(property => [property, ''])), + }); +} + +// Document listeners added and not yet removed, by type. +let documentListeners: Map; +const realAdd = document.addEventListener.bind(document); +const realRemove = document.removeEventListener.bind(document); +let open: Set; +const realShow = HTMLElement.prototype.showPopover; +const realHide = HTMLElement.prototype.hidePopover; +const realMatches = Element.prototype.matches; + +beforeEach(() => { + vi.useFakeTimers(); + open = new Set(); + HTMLElement.prototype.showPopover = function (this: HTMLElement) { + open.add(this); + }; + HTMLElement.prototype.hidePopover = function (this: HTMLElement) { + open.delete(this); + }; + // jsdom knows no popover state: `:popover-open` is this stand-in's. + Element.prototype.matches = function (this: Element, selector: string) { + return selector === ':popover-open' + ? open.has(this) + : realMatches.call(this, selector); + } as typeof realMatches; + documentListeners = new Map(); + vi.spyOn(document, 'addEventListener').mockImplementation( + (type, listener, opts) => { + documentListeners.set(type, (documentListeners.get(type) ?? 0) + 1); + const signal = + typeof opts === 'object' && opts != null ? opts.signal : undefined; + signal?.addEventListener('abort', () => { + documentListeners.set(type, (documentListeners.get(type) ?? 1) - 1); + }); + realAdd(type, listener, opts); + }, + ); + vi.spyOn(document, 'removeEventListener').mockImplementation( + (type, listener, opts) => { + documentListeners.set(type, (documentListeners.get(type) ?? 1) - 1); + realRemove(type, listener, opts); + }, + ); + vi.mocked(holdPresentation).mockClear(); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + HTMLElement.prototype.showPopover = realShow; + HTMLElement.prototype.hidePopover = realHide; + Element.prototype.matches = realMatches; + document.body.innerHTML = ''; +}); + +/** Every listener this test added to the document is gone. */ +function expectNoDocumentListeners() { + for (const [type, live] of documentListeners) { + expect({type, live: Math.max(live, 0)}).toEqual({type, live: 0}); + } +} + +describe('lift', () => { + it('adds the layer, its shadow and anchor, and one placeholder while lifted, whatever the source holds; the source keeps its place among its siblings', () => { + const {source, before} = renderList(); + const rest = count(); + const lift = createLift(); + const result = lift.lift(source, options()); + expect(result).not.toBeNull(); + // 13 elements lifted (the row and its 12), 4 added. + expect(count()).toBe(rest + 4); + expect(source.previousElementSibling).toBe(before); + const placeholder = source.nextElementSibling as HTMLElement; + expect(placeholder.hasAttribute('data-test-lift-placeholder')).toBe(true); + expect(placeholder.getAttribute('aria-hidden')).toBe('true'); + expect(placeholder.style.width).toBe('335px'); + expect(placeholder.style.height).toBe('60px'); + const layer = document.body.lastElementChild as HTMLElement; + expect(layer.hasAttribute('data-test-lift')).toBe(true); + expect(layer.getAttribute('popover')).toBe('manual'); + // The box a surface is placed against: the lifted rect, in the layer. + expect(result?.anchor.parentElement).toBe(layer); + expect(result?.anchor.style.width).toBe(`${result?.lifted.width}px`); + // The source itself is in the top layer, above the layer, at its box, + // and takes no hits. + expect(source.getAttribute('popover')).toBe('manual'); + expect([...open]).toEqual([layer, source]); + expect(source.style.getPropertyValue('position')).toBe('fixed'); + expect(source.style.getPropertyValue('left')).toBe('20px'); + expect(source.style.getPropertyValue('top')).toBe('300px'); + expect(source.style.getPropertyValue('width')).toBe('335px'); + expect(source.style.getPropertyValue('pointer-events')).toBe('none'); + expect(lift.isLifted()).toBe(true); + // Grown about its center by 26 px on its larger side. + expect(result?.lifted.width).toBeCloseTo(361, 5); + lift.dispose(); + }); + + it("resolves the layer runtime's gutter on each edge in px where the source is, with the app's declared inset, and the source's direction", () => { + const {source} = renderList(); + const original = window.getComputedStyle.bind(window); + let declaredInset = ''; + const gutter: Record = { + 'padding-top': '47px', + 'padding-bottom': '34px', + 'padding-left': '16px', + }; + vi.spyOn(window, 'getComputedStyle').mockImplementation( + (element, pseudo) => { + const style = original(element, pseudo); + // The source's direction, and the gutter as resolved inside it. + if (element === source) { + const rtl: CSSStyleDeclaration = { + ...style, + direction: 'rtl', + getPropertyValue: (property: string) => + style.getPropertyValue(property), + }; + return rtl; + } + if (element.parentElement !== source) { + return style; + } + declaredInset = (element as HTMLElement).style.getPropertyValue( + '--astryx-layer-inset-block-end', + ); + const resolved: CSSStyleDeclaration = { + ...style, + getPropertyValue: (property: string) => + gutter[property] ?? style.getPropertyValue(property), + }; + return resolved; + }, + ); + const lift = createLift(); + const result = lift.lift(source, options({inset: {blockEnd: 56}})); + expect(declaredInset).toBe('56px'); + expect(result?.viewport.gutter).toEqual({top: 47, bottom: 34, inline: 16}); + expect(result?.viewport.direction).toBe('rtl'); + lift.dispose(); + }); + + it('a drop puts back exactly what the source had inline, and takes the placeholder and the layer away', async () => { + const {source} = renderList(); + const rest = count(); + const lift = createLift(); + lift.lift(source, options()); + lift.drop(); + await vi.runAllTimersAsync(); + expectInlineAsBefore(source); + expect(source.hasAttribute('popover')).toBe(false); + expect(count()).toBe(rest); + expect(open.size).toBe(0); + expect(lift.isLifted()).toBe(false); + }); + + it('an unmount mid-lift ends it at once: no element, document listener or timer left', () => { + const {source} = renderList(); + const rest = count(); + const lift = createLift(); + lift.lift(source, options()); + lift.dispose(); + expectInlineAsBefore(source); + expect(count()).toBe(rest); + expect(open.size).toBe(0); + expectNoDocumentListeners(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('an unmount while the close waits for a press on the layer to lift leaves nothing behind either', async () => { + const {source} = renderList(); + const rest = count(); + const lift = createLift(); + lift.lift(source, options()); + const layer = document.body.lastElementChild as HTMLElement; + // A finger down on the layer, never lifted: the close waits for it. + const down = new Event('pointerdown', {bubbles: true}); + Object.assign(down, {pointerId: 7, isPrimary: true}); + layer.dispatchEvent(down); + lift.drop(); + await vi.runAllTimersAsync(); + expect(document.body.contains(layer)).toBe(true); + lift.dispose(); + expect(count()).toBe(rest); + expectNoDocumentListeners(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('twenty lifts and drops leave the page, the document listeners and the timers as they were (no leaks)', async () => { + const {source} = renderList(); + const rest = count(); + const lift = createLift(); + for (let i = 0; i < 20; i++) { + lift.lift(source, options()); + lift.drop(); + await vi.runAllTimersAsync(); + } + expect(count()).toBe(rest); + expectInlineAsBefore(source); + expectNoDocumentListeners(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('changes nothing without the popover API', () => { + const {source} = renderList(); + const html = document.body.innerHTML; + // @ts-expect-error: a browser without the popover API. + HTMLElement.prototype.showPopover = undefined; + const lift = createLift(); + expect(lift.lift(source, options())).toBeNull(); + expect(document.body.innerHTML).toBe(html); + }); + + it('a source out of the flow needs no placeholder', () => { + const {source} = renderList(); + source.style.position = 'absolute'; + const rest = count(); + const lift = createLift(); + lift.lift(source, options()); + expect(count()).toBe(rest + 3); + lift.dispose(); + }); + + it('holds the layer while the source grows and a surface grows (a presentation), and while it closes (the layer)', async () => { + const {source} = renderList(); + document.body.insertAdjacentHTML( + 'beforeend', + '', + ); + const menu = document.getElementById('menu') as HTMLElement; + place(menu, 40, 380, 250, 200); + const lift = createLift(); + lift.lift(source, options()); + const layer = document.querySelector('[data-test-lift]'); + expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + scope: 'viewport', + until: expect.any(Promise), + }); + vi.mocked(holdPresentation).mockClear(); + lift.presentSurface( + menu.querySelector('[role="menu"]') as HTMLElement, + {x: 180, y: 330}, + ); + expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + scope: 'viewport', + until: expect.any(Promise), + }); + lift.drop(); + expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + scope: 'layer', + until: expect.any(Promise), + }); + await vi.runAllTimersAsync(); + lift.dispose(); + }); + + it('a press that went down and lifted on the layer is a backdrop tap; one that came from elsewhere is not', () => { + const {source} = renderList(); + const onBackdropTap = vi.fn(); + const lift = createLift(); + lift.lift(source, options({onBackdropTap})); + const layer = document.body.lastElementChild as HTMLElement; + const pointer = (type: string, pointerId: number) => { + const event = new Event(type, {bubbles: true}); + Object.assign(event, {pointerId, isPrimary: true}); + layer.dispatchEvent(event); + }; + // The finger that opened the menu lifts on the layer: not a tap there. + pointer('pointerup', 1); + expect(onBackdropTap).not.toHaveBeenCalled(); + pointer('pointerdown', 2); + pointer('pointerup', 2); + expect(onBackdropTap).toHaveBeenCalledTimes(1); + lift.dispose(); + }); +}); diff --git a/packages/core/src/lift/lift.ts b/packages/core/src/lift/lift.ts new file mode 100644 index 0000000000000..e51d603df90a9 --- /dev/null +++ b/packages/core/src/lift/lift.ts @@ -0,0 +1,1270 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file lift.ts + * @input An element to lift (the source) and, beside it, a surface that + * grows out of the press (a menu's popover); the caller's springs (motion + * roles a theme may retune), scale rule and tint; the rect morph + * (motion/rectMorph.ts); the layer runtime's presentation hold, exit copy, + * viewport gutter and declared inset + * @output Exports createLift: lift a source out of the page above a tinted + * backdrop, grow a surface out of the press beside it, shrink the surface + * back into the press, and return the source to its place + * @position The one lift-from-trigger presentation, internal to core and + * opt-in: only a surface that chooses it uses it (ContextMenu's touch + * invocation today). Layer stays generic: the top layer, dismissal, the + * presentation hold and the shared exit copy are its; this module only + * uses them + * + * UIKit's context menu lifts the long-pressed view out of the page: it grows + * on from the size the press gave it to its lifted size, a shadow rising + * under it, above a backdrop that tints the page; the menu grows out of the + * finger beside it, and when the menu closes it shrinks back into the finger + * while the view returns to its place and the backdrop clears. + * + * Here the source itself lifts, not a copy: it becomes a manual popover in + * the top layer, laid out at its own size where it stood, so no clipping, + * transformed or stacking ancestor cuts or covers it, while one empty + * placeholder holds its spot in the page, which does not move. What the + * browser's popover style would change (border, padding, colors, overflow) is + * kept as it was laid out, and the source takes no hits while lifted (a tap + * on it is a tap on the backdrop). Inheritance follows the DOM, so the page's + * theme still reaches it. The placeholder goes after the source, so the + * source keeps its place among its siblings. The tint is the `::backdrop` of + * a lift layer at the end of the body that covers the viewport and takes the + * page's touches (its color and the gutter's spacing resolved where the + * source is); the shadow is a box in the layer that follows the source on a + * rect morph of its own (an animated `::backdrop` of the source would + * restyle and lay out the page on every frame). The layer also holds an empty box + * at the lifted rect for a surface to be placed against: anchor positioning + * follows transforms, so a box inside the source would move with it. Nothing + * of the lift is in the DOM at rest; while lifted it adds four elements, the + * layer, the shadow, the box and the placeholder + * (`architecture:component-style-authoring` INV7, `spec:AST-017` FR60), and + * its close plays on the layer runtime's one exit copy + * (`placeLayerExitCopy`). + * + * Every motion is `translate`, `scale` or `opacity` on the compositor + * (spec:AST-094 FR5): the source and the surface on the rect morph, which + * interrupts itself with the velocity on screen (FR6), the shadow on one of + * its own along the same path; the tint as a spring-sampled Web Animation of + * the layer's `::backdrop`. A tap or + * a drag that lands while the lift and the surface grow reaches nothing + * (the presentation hold, FR35); the close holds the layer until the source + * is back, the surface's exit is done and every press on the layer has + * lifted. Its timers and document listeners end with it (FR24). Reduce + * Motion is the animator's (design:reduced-motion): opacity only. + * + * SYNC: When modified, update: + * - /packages/core/src/lift/lift.test.ts + * - /packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts + */ + +import type {LayerInset} from '../Layer/LayerContext'; +import {placeLayerExitCopy} from '../Layer/layerExitCopy'; +import {layerInsetProperties} from '../Layer/layerInset'; +import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; +import {holdPresentation} from '../Layer/presentationHold'; +import type {MotionHandle} from '../motion/animator'; +import {progressCurve} from '../motion/progress'; +import { + createRectMorph, + lerpPath, + type MorphPath, + type MorphRect, + type RectMorph, +} from '../motion/rectMorph'; +import {reducedMotionFade} from '../motion/reducedMotion'; +import {resolveMotion} from '../motion/resolveMotion'; +import { + SETTLING_EPSILON, + solveSpring, + toSpring, + type SpringDescription, +} from '../motion/spring'; +import { + liftedRect, + type LiftScaleRule, + type LiftViewport, +} from './liftGeometry'; + +/** + * How long the layer waits, once the last pointer that went down on it has + * lifted, for that touch's click before it hides anyway (a long press sends + * none). + */ +const CLICK_AFTER_LIFT_MS = 350; + +/** The springs of a lift; the caller's motion roles. */ +export interface LiftMotion { + /** The source grows to its lifted rect on it, and the tint fades in. */ + readonly lift: SpringDescription; + /** The source returns to its place on it. */ + readonly drop: SpringDescription; + /** The tint clears on it. */ + readonly clear: SpringDescription; + /** The shadow rises on it. */ + readonly shadowIn: SpringDescription; + /** The shadow fades on it. */ + readonly shadowOut: SpringDescription; + /** A surface grows out of the press on it. */ + readonly surfaceIn: SpringDescription; + /** A surface shrinks back into the press on it. */ + readonly surfaceOut: SpringDescription; +} + +export interface LiftOptions { + readonly motion: LiftMotion; + /** How far the source grows. */ + readonly scale: LiftScaleRule; + /** + * The width a surface grows out of, centered on the press (its height + * keeps the surface's aspect); a point by default. + */ + readonly surfaceStartWidth?: number; + /** + * The rect the source grows on from, viewport px: where a press feedback + * left it. Its box as laid out by default. + */ + readonly from?: MorphRect; + /** + * Called once the lift has read the page and before it writes to it: lets + * go of what the source was doing (a press feedback's scale), so letting go + * doesn't restyle the page before the lift reads it. + */ + readonly release?: () => void; + /** The tint, a CSS color resolved where the source is. */ + readonly tint?: string; + /** The shadow under the lifted source, a CSS box shadow. */ + readonly shadow?: string; + /** The inset an app declares for a bar over an edge (LayerProvider). */ + readonly inset?: LayerInset; + /** A finger lifted on the backdrop where it went down. */ + readonly onBackdropTap?: () => void; + /** + * Marks the lift's elements: the layer, its placeholder + * (`-placeholder`) and a surface's exit copy + * (`-exit`). + */ + readonly attribute?: string; +} + +/** Where a lift landed. */ +export interface LiftResult { + /** The source's box as laid out, viewport px. */ + readonly source: MorphRect; + /** The rect it lands on. */ + readonly lifted: MorphRect; + /** The viewport and the layer runtime's gutter it lifted in. */ + readonly viewport: LiftViewport; + /** + * An empty box at the lifted rect, in the layer: what a surface is placed + * against (an anchor inside the source would move with the source's + * transform, which anchor positioning follows). + */ + readonly anchor: HTMLElement; +} + +export interface Lift { + /** + * Lifts `source`: returns where it lands, or null without the popover API + * (nothing changes then). A lift already up ends at once. + */ + lift(source: HTMLElement, options: LiftOptions): LiftResult | null; + /** + * Grows `surface` (a popover laid out at rest, or an element inside one) + * out of `press` (client px) into its box, or, without a press, fades it + * in where it rests; and holds the lift until the lift and the surface + * settle (spec:AST-094 FR35). A no-op when nothing is lifted. + */ + presentSurface( + surface: HTMLElement, + press?: {x: number; y: number} | null, + ): void; + /** + * The surface is closing: its exit copy shrinks back into the press from + * wherever it stands. Call it while the surface still shows. + */ + dismissSurface(surface: HTMLElement): void; + /** Returns the source to its place; the layer leaves once it is back. */ + drop(): void; + /** Ends everything at once and leaves the page as it was. */ + dispose(): void; + /** Whether a source is lifted. */ + isLifted(): boolean; +} + +type SavedStyle = [property: string, value: string, priority: string][]; + +interface LiftedSurface { + readonly element: HTMLElement; + readonly morph: RectMorph; + readonly path: MorphPath; + readonly press: {x: number; y: number}; + presenting: MotionHandle | null; + dismissing: MotionHandle | null; +} + +interface LiftState { + readonly generation: number; + readonly options: LiftOptions; + /** The springs, as the source's theme set them at the lift. */ + readonly motion: LiftMotion; + readonly attribute: string; + readonly source: HTMLElement; + readonly sourceRect: MorphRect; + readonly lifted: MorphRect; + readonly layer: HTMLElement; + readonly placeholder: HTMLElement | null; + readonly saved: SavedStyle; + readonly transition: [value: string, priority: string]; + readonly morph: RectMorph; + readonly growing: MotionHandle; + /** The tint's color, held on the layer's `::backdrop`. */ + readonly layerFill: Animation | null; + /** + * The shadow under the source: a box in the layer laid out where the + * source is, which follows it frame for frame and fades on its own spring. + */ + readonly shadow: HTMLElement; + shadowAnimation: Animation | null; + /** + * Holds the source morph's clock at one instant (null lets it run), so the + * shadow reads the motion at the very moment the morph does. + */ + readonly holdClock: (at: number | null) => void; + /** The layer's own waits and listeners, released with it (FR24). */ + readonly waits: AbortController; + untilPointersLift: () => Promise; + tint: Animation | null; + surface: LiftedSurface | null; + releaseGrowHold: (() => void) | null; + releaseHold: (() => void) | null; + isSourceLifted: boolean; +} + +const px = (value: string | undefined) => Number.parseFloat(value ?? '') || 0; + +/** + * Sets `values` on `element` inline, `!important`, recording what was there + * for `restore`. + */ +function setInline( + element: HTMLElement, + values: Record, + saved: SavedStyle, +): void { + for (const [property, value] of Object.entries(values)) { + saved.push([ + property, + element.style.getPropertyValue(property), + element.style.getPropertyPriority(property), + ]); + element.style.setProperty(property, value, 'important'); + } +} + +function restore(element: HTMLElement, saved: SavedStyle): void { + for (let i = saved.length - 1; i >= 0; i--) { + const [property, value, priority] = saved[i]; + if (value === '') { + element.style.removeProperty(property); + } else { + element.style.setProperty(property, value, priority); + } + } +} + +/** Web Animation keyframes along `spring` from 0 to 1, sampled at 60 Hz. */ +function springKeyframes( + element: Element, + spring: SpringDescription, + frame: (progress: number) => Keyframe, +): {keyframes: Keyframe[]; duration: number} { + const curve = solveSpring(toSpring(resolveMotion(element, spring)), { + from: 0, + to: 1, + }); + const seconds = Math.max(curve.settleTime(SETTLING_EPSILON), 1 / 60); + const steps = Math.max(2, Math.ceil(seconds * 60)); + const keyframes: Keyframe[] = []; + for (let i = 0; i <= steps; i++) { + const t = (i / steps) * seconds; + keyframes.push({ + ...frame(i === steps ? 1 : curve.value(t)), + offset: i / steps, + }); + } + return {keyframes, duration: seconds * 1000}; +} + +/** + * Web Animation keyframes for a box laid out on `box` that travels from + * `from` to `to` on `travel` (starting with progress velocity `velocity`, as + * the rect morph does) while its opacity goes from `fade[0]` to `fade[1]` on + * `fadeSpring`, sampled at 60 Hz until both settle: one compositor animation + * of `transform` and `opacity`, frame for frame with the source's own morph. + */ +function shadowKeyframes( + box: MorphRect, + from: MorphRect, + to: MorphRect, + travel: SpringDescription | null, + fade: readonly [number, number], + fadeSpring: SpringDescription, + velocity = 0, +): {keyframes: Keyframe[]; duration: number} { + const move = travel == null ? null : progressCurve(travel, {velocity}); + const opacity = progressCurve(fadeSpring); + const seconds = Math.max(move?.duration ?? 0, opacity.duration, 1 / 60); + const steps = Math.max(2, Math.ceil(seconds * 60)); + const keyframes: Keyframe[] = []; + for (let i = 0; i <= steps; i++) { + const t = (i / steps) * seconds; + const p = i === steps || move == null ? 1 : move.at(t); + const q = i === steps ? 1 : opacity.at(t); + const rect = { + x: from.x + (to.x - from.x) * p, + y: from.y + (to.y - from.y) * p, + width: from.width + (to.width - from.width) * p, + }; + const scale = box.width > 0 ? rect.width / box.width : 1; + keyframes.push({ + transform: `translate(${(rect.x - box.x).toFixed(3)}px, ${(rect.y - box.y).toFixed(3)}px) scale(${scale.toFixed(5)})`, + opacity: String( + Math.min(Math.max(fade[0] + (fade[1] - fade[0]) * q, 0), 1), + ), + offset: i / steps, + }); + } + return {keyframes, duration: seconds * 1000}; +} + +/** Plays `keyframes` on `element`, or only their ends under Reduce Motion. */ +function playShadow( + element: HTMLElement, + {keyframes, duration}: {keyframes: Keyframe[]; duration: number}, + reduced: ReturnType, +): Animation | null { + if (typeof element.animate !== 'function') { + return null; + } + return element.animate( + reduced == null + ? keyframes + : [keyframes[0], keyframes[keyframes.length - 1]], + { + duration: reduced?.duration ?? duration, + easing: reduced?.easing ?? 'linear', + fill: 'forwards', + }, + ); +} + +/** + * The radius of the shape `source` shows: its own, or that of its only + * element child when that child fills it. + */ +function shapeRadius(source: HTMLElement): string { + const view = source.ownerDocument.defaultView; + const own = view?.getComputedStyle(source).borderRadius ?? ''; + if (px(own) > 0 || source.children.length === 0) { + return own; + } + const outer = source.getBoundingClientRect(); + for (const child of source.children) { + const inner = child.getBoundingClientRect(); + if ( + Math.abs(inner.width - outer.width) <= 1 && + Math.abs(inner.height - outer.height) <= 1 + ) { + return view?.getComputedStyle(child).borderRadius ?? own; + } + } + return own; +} + +/** + * Resolves CSS values where `element` is (its theme, its color scheme): on an + * empty, undisplayed child it removes again, so the element's own style and + * the page's layout stay as they were. A pair is a fallback and a value a + * browser may reject. + */ +function probe( + element: HTMLElement, + values: Record, +): Record { + const doc = element.ownerDocument; + const child = doc.createElement('span'); + child.style.setProperty('display', 'none'); + for (const [property, value] of Object.entries(values)) { + if (typeof value === 'string') { + child.style.setProperty(property, value); + } else { + child.style.setProperty(property, value[0]); + child.style.setProperty(property, value[1]); + } + } + element.append(child); + const style = doc.defaultView?.getComputedStyle(child); + const resolved: Record = {}; + for (const property of Object.keys(values)) { + resolved[property] = style?.getPropertyValue(property) ?? ''; + } + child.remove(); + return resolved; +} + +/** + * The lift's springs as `element`'s theme sets them, read once: plain + * springs, which nothing reads from the page again. + */ +function resolvedMotion(element: Element, motion: LiftMotion): LiftMotion { + const resolve = (spring: SpringDescription): SpringDescription => ({ + ...resolveMotion(element, spring), + }); + return { + lift: resolve(motion.lift), + drop: resolve(motion.drop), + clear: resolve(motion.clear), + shadowIn: resolve(motion.shadowIn), + shadowOut: resolve(motion.shadowOut), + surfaceIn: resolve(motion.surfaceIn), + surfaceOut: resolve(motion.surfaceOut), + }; +} + +/** Plays `keyframes` on `element`'s `::backdrop`, holding the end. */ +function animateBackdrop( + element: HTMLElement, + keyframes: Keyframe[], + options: KeyframeAnimationOptions, +): Animation | null { + if (typeof element.animate !== 'function') { + return null; + } + try { + return element.animate(keyframes, { + fill: 'forwards', + ...options, + pseudoElement: '::backdrop', + }); + } catch { + // No `::backdrop` animations: the lift shows without its decoration. + return null; + } +} + +/** The `::backdrop` opacity `element` shows now, or `fallback`. */ +function backdropOpacity(element: HTMLElement, fallback: number): number { + try { + const shown = Number.parseFloat( + getComputedStyle(element, '::backdrop').opacity, + ); + return Number.isFinite(shown) ? shown : fallback; + } catch { + return fallback; + } +} + +/** + * Fades `element`'s `::backdrop` to `to` on `spring`, from `from` or what it + * shows; `reduced` is the Reduce Motion fade when read already. Opacity + * alone, so the compositor plays it. + */ +function fadeBackdrop( + element: HTMLElement, + to: number, + spring: SpringDescription, + { + from = backdropOpacity(element, to === 1 ? 0 : 1), + reduced = reducedMotionFade(element), + }: {from?: number; reduced?: ReturnType} = {}, +): Animation | null { + if (reduced != null) { + return animateBackdrop( + element, + [{opacity: String(from)}, {opacity: String(to)}], + {duration: reduced.duration, easing: reduced.easing}, + ); + } + const {keyframes, duration} = springKeyframes(element, spring, p => ({ + opacity: String(from + (to - from) * p), + })); + return animateBackdrop(element, keyframes, {duration}); +} + +/** + * The lift layer: covers the viewport from the top layer and takes the + * page's touches while the source is up; its `::backdrop` is the tint. + */ +function createLayer(doc: Document, attribute: string): HTMLElement { + const layer = doc.createElement('span'); + layer.setAttribute('popover', 'manual'); + layer.setAttribute('aria-hidden', 'true'); + layer.setAttribute(attribute, ''); + Object.assign(layer.style, { + position: 'fixed', + inset: '0', + width: '100%', + height: '100%', + maxWidth: 'none', + maxHeight: 'none', + margin: '0', + padding: '0', + border: '0', + backgroundColor: 'transparent', + color: 'inherit', + overflow: 'visible', + pointerEvents: 'auto', + touchAction: 'none', + }); + return layer; +} + +/** + * The placeholder that holds a source's spot in the page while it is lifted: + * empty, hidden, at its laid-out size, with its margins and its place in a + * flex or grid container. + */ +function placeholderStyle( + computed: CSSStyleDeclaration, + box: MorphRect, +): Partial { + const display = + computed.display === 'inline' + ? 'inline-block' + : computed.display === 'contents' || computed.display === 'none' + ? 'block' + : computed.display; + return { + display, + boxSizing: 'border-box', + width: `${box.width}px`, + height: `${box.height}px`, + marginTop: computed.marginTop, + marginRight: computed.marginRight, + marginBottom: computed.marginBottom, + marginLeft: computed.marginLeft, + flexGrow: computed.flexGrow, + flexShrink: computed.flexShrink, + flexBasis: computed.flexBasis, + alignSelf: computed.alignSelf, + justifySelf: computed.justifySelf, + order: computed.order, + gridRowStart: computed.gridRowStart, + gridRowEnd: computed.gridRowEnd, + gridColumnStart: computed.gridColumnStart, + gridColumnEnd: computed.gridColumnEnd, + cssFloat: computed.cssFloat, + verticalAlign: computed.verticalAlign, + visibility: 'hidden', + pointerEvents: 'none', + }; +} + +/** The properties the browser's popover style sets, kept as laid out. */ +const KEPT_PROPERTIES = [ + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width', + 'border-top-style', + 'border-right-style', + 'border-bottom-style', + 'border-left-style', + 'border-top-color', + 'border-right-color', + 'border-bottom-color', + 'border-left-color', + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left', + 'color', + 'background-color', + 'overflow-x', + 'overflow-y', +] as const; + +/** Creates a lift; one per component that offers it. */ +export function createLift(): Lift { + let state: LiftState | null = null; + let generation = 0; + + const releaseGrowHold = (current: LiftState) => { + current.releaseGrowHold?.(); + current.releaseGrowHold = null; + }; + + // Puts the source back in the page as it was laid out. + const settleSource = (current: LiftState) => { + if (!current.isSourceLifted) { + return; + } + current.isSourceLifted = false; + const {source} = current; + current.shadowAnimation?.cancel(); + current.shadowAnimation = null; + current.morph.dispose(); + if (source.matches(':popover-open')) { + source.hidePopover(); + } + source.removeAttribute('popover'); + restore(source, current.saved); + current.placeholder?.remove(); + // The restored values apply before the source's own transitions return, + // so none of them animates. + void source.ownerDocument.defaultView?.getComputedStyle(source).width; + const [value, priority] = current.transition; + if (value === '') { + source.style.removeProperty('transition'); + } else { + source.style.setProperty('transition', value, priority); + } + }; + + const endSurface = (current: LiftState) => { + const surface = current.surface; + current.surface = null; + surface?.morph.dispose(); + }; + + const hideLayer = (current: LiftState) => { + releaseGrowHold(current); + current.releaseHold?.(); + current.releaseHold = null; + current.waits.abort(); + current.tint?.cancel(); + current.tint = null; + current.layerFill?.cancel(); + const {layer} = current; + if (layer.matches(':popover-open')) { + layer.hidePopover(); + } + layer.remove(); + }; + + const end = (current: LiftState) => { + endSurface(current); + settleSource(current); + hideLayer(current); + if (state === current) { + state = null; + } + }; + + // Every pointer that went down on the layer and is still down (the tint + // while it presents, the hold's shield while it closes), read from the + // document so an inert target hides none; and whether the last one to lift + // still owes its click (a touch's click comes after its pointer's up). + const watchPointers = (current: LiftState) => { + const {layer, waits} = current; + const doc = layer.ownerDocument; + const pointers = new Set(); + let isClickPending = false; + const options = {capture: true, signal: waits.signal}; + doc.addEventListener( + 'pointerdown', + event => { + if (event.composedPath().includes(layer)) { + pointers.add(event.pointerId); + } + }, + options, + ); + const up = (event: PointerEvent) => { + if (pointers.delete(event.pointerId) && event.type === 'pointerup') { + isClickPending = true; + } + }; + doc.addEventListener('pointerup', up, options); + doc.addEventListener('pointercancel', up, options); + doc.addEventListener( + 'click', + () => { + isClickPending = false; + }, + options, + ); + // Settles once no pointer is down on the layer and the last one's click + // has landed too, or shortly after (a long press sends none). + return async (): Promise => + new Promise(resolve => { + const wait = () => { + if (waits.signal.aborted) { + return; + } + if (pointers.size > 0) { + const lifted = () => { + if (pointers.size > 0) { + return; + } + doc.removeEventListener('pointerup', lifted, true); + doc.removeEventListener('pointercancel', lifted, true); + wait(); + }; + doc.addEventListener('pointerup', lifted, options); + doc.addEventListener('pointercancel', lifted, options); + return; + } + if (!isClickPending) { + resolve(); + return; + } + const timer = setTimeout(finish, CLICK_AFTER_LIFT_MS); + waits.signal.addEventListener('abort', () => clearTimeout(timer), { + once: true, + }); + function finish() { + doc.removeEventListener('click', finish, true); + clearTimeout(timer); + isClickPending = false; + wait(); + } + doc.addEventListener('click', finish, options); + }; + wait(); + }); + }; + + const lift = ( + source: HTMLElement, + options: LiftOptions, + ): LiftResult | null => { + if (state != null) { + end(state); + } + if (typeof source.showPopover !== 'function' || !source.isConnected) { + return null; + } + const attribute = options.attribute ?? 'data-astryx-lift'; + const doc = source.ownerDocument; + const view = doc.defaultView; + const computed = view?.getComputedStyle(source); + if (computed == null) { + return null; + } + // The lift reads everything before it writes to the page, so the page + // restyles and lays out once for it. + // The source as laid out (a scale on it, the press feedback's, is about + // its center). + const shown = source.getBoundingClientRect(); + const width = source.offsetWidth || shown.width; + const height = source.offsetHeight || shown.height; + const sourceRect: MorphRect = { + x: shown.left + (shown.width - width) / 2, + y: shown.top + (shown.height - height) / 2, + width, + height, + }; + const from = options.from ?? sourceRect; + // What it keeps of its look and its layout. + const kept: Record = {}; + for (const property of KEPT_PROPERTIES) { + kept[property] = computed.getPropertyValue(property); + } + const isInFlow = + computed.position !== 'absolute' && computed.position !== 'fixed'; + const placeholderValues = isInFlow + ? placeholderStyle(computed, sourceRect) + : null; + const direction = computed.direction === 'rtl' ? 'rtl' : 'ltr'; + const radius = shapeRadius(source); + const motion = resolvedMotion(source, options.motion); + const reduced = reducedMotionFade(source); + // The tint, the shadow and the layer runtime's gutter (spec:AST-059, + // with the inset an app declares), resolved where the source is. + const probed = probe(source, { + ...Object.fromEntries( + Object.entries(layerInsetProperties(options.inset)).map( + ([property, value]) => [property, String(value)], + ), + ), + 'background-color': options.tint ?? 'var(--color-overlay)', + 'box-shadow': options.shadow ?? 'var(--shadow-high)', + 'padding-top': [ + `calc(${layerViewportInset.gutterBlockStartFallback})`, + `calc(${layerViewportInset.gutterBlockStart})`, + ], + 'padding-bottom': [ + `calc(${layerViewportInset.gutterBlockEndFallback})`, + `calc(${layerViewportInset.gutterBlockEnd})`, + ], + 'padding-left': [ + `calc(${layerViewportInset.gutterInlineFallback})`, + `calc(${layerViewportInset.gutterInline})`, + ], + }); + const tint = probed['background-color']; + const shadow = probed['box-shadow']; + const viewport: LiftViewport = { + width: doc.documentElement.clientWidth || view?.innerWidth || 0, + height: view?.innerHeight ?? doc.documentElement.clientHeight, + gutter: { + top: px(probed['padding-top']), + bottom: px(probed['padding-bottom']), + inline: px(probed['padding-left']), + }, + direction, + }; + const lifted = liftedRect(sourceRect, viewport, options.scale); + // Writes from here on. + options.release?.(); + const layer = createLayer(doc, attribute); + doc.body.append(layer); + const shadowEl = doc.createElement('span'); + shadowEl.setAttribute(`${attribute}-shadow`, ''); + Object.assign(shadowEl.style, { + position: 'absolute', + left: `${sourceRect.x}px`, + top: `${sourceRect.y}px`, + width: `${sourceRect.width}px`, + height: `${sourceRect.height}px`, + borderRadius: radius, + boxShadow: shadow, + opacity: '0', + pointerEvents: 'none', + // Its keyframes scale about the top-left corner, as the source's do. + transformOrigin: '0 0', + }); + layer.append(shadowEl); + const anchor = doc.createElement('span'); + anchor.setAttribute(`${attribute}-anchor`, ''); + Object.assign(anchor.style, { + position: 'absolute', + left: `${lifted.x}px`, + top: `${lifted.y}px`, + width: `${lifted.width}px`, + height: `${lifted.height}px`, + pointerEvents: 'none', + }); + layer.append(anchor); + let placeholder: HTMLElement | null = null; + if (placeholderValues != null) { + placeholder = doc.createElement('span'); + placeholder.setAttribute(`${attribute}-placeholder`, ''); + placeholder.setAttribute('aria-hidden', 'true'); + Object.assign(placeholder.style, placeholderValues); + } + generation += 1; + const transition: [string, string] = [ + source.style.getPropertyValue('transition'), + source.style.getPropertyPriority('transition'), + ]; + const saved: SavedStyle = []; + // No transition of its own reacts to the lift's values. + source.style.setProperty('transition', 'none', 'important'); + setInline( + source, + { + // Longhands only: each is put back as it was. + position: 'fixed', + left: `${sourceRect.x}px`, + top: `${sourceRect.y}px`, + right: 'auto', + bottom: 'auto', + width: `${sourceRect.width}px`, + height: `${sourceRect.height}px`, + 'min-width': '0', + 'min-height': '0', + 'max-width': 'none', + 'max-height': 'none', + 'margin-top': '0', + 'margin-right': '0', + 'margin-bottom': '0', + 'margin-left': '0', + 'box-sizing': 'border-box', + ...kept, + 'pointer-events': 'none', + }, + saved, + ); + if (placeholder != null) { + source.after(placeholder); + } + source.setAttribute('popover', 'manual'); + const waits = new AbortController(); + // The source grows out of where the press left it into its lifted rect, + // laid out at its own size, so its content scales as UIKit's snapshot + // does. Under Reduce Motion it lands at once and fades in. + let heldAt: number | null = null; + const holdClock = (at: number | null) => { + heldAt = at; + }; + const morph = createRectMorph(source, { + now: () => heldAt ?? performance.now(), + }); + // The layer first: the source shows above its tint. + layer.showPopover(); + source.showPopover(); + holdClock(performance.now()); + const growing = morph.present( + lerpPath(from, lifted, {box: sourceRect, scale: 'uniform'}), + motion.lift, + {crossfadeAs: 'entrance'}, + ); + holdClock(null); + // The tint: the layer's `::backdrop`, its color held there. + const layerFill = animateBackdrop( + layer, + [ + {backgroundColor: tint, opacity: '0'}, + {backgroundColor: tint, opacity: '0'}, + ], + {duration: 0}, + ); + // The shadow rises with the source: it follows the source's path on the + // lift's spring and fades in on its own, from the frame the source starts + // in, as one compositor animation (an animated `::backdrop` of the source + // would restyle and lay out the page on every frame). Under Reduce Motion + // it fades in where the source lands. + const rise = playShadow( + shadowEl, + reduced == null + ? shadowKeyframes( + sourceRect, + from, + lifted, + motion.lift, + [0, 1], + motion.shadowIn, + ) + : shadowKeyframes( + sourceRect, + lifted, + lifted, + null, + [0, 1], + motion.shadowIn, + ), + reduced, + ); + void growing.started.then(at => { + if (rise != null && current.shadowAnimation === rise) { + rise.startTime = at; + } + }); + const current: LiftState = { + generation, + options, + motion, + attribute, + source, + sourceRect, + lifted, + layer, + placeholder, + saved, + transition, + morph, + growing, + layerFill, + shadow: shadowEl, + shadowAnimation: rise, + holdClock, + waits, + untilPointersLift: async () => {}, + tint: fadeBackdrop(layer, 1, motion.lift, {from: 0, reduced}), + surface: null, + releaseGrowHold: null, + releaseHold: null, + isSourceLifted: true, + }; + state = current; + // Taps on the backdrop: only a pointer that went down on the layer lifts + // there (WebKit hands the layer the lift of the finger that opened the + // menu). + let backdropPointer: number | null = null; + const listen = {signal: waits.signal}; + layer.addEventListener( + 'pointerdown', + event => { + backdropPointer = event.isPrimary ? event.pointerId : null; + }, + listen, + ); + layer.addEventListener( + 'pointerup', + event => { + const wentDownHere = backdropPointer === event.pointerId; + backdropPointer = null; + if (wentDownHere) { + current.options.onBackdropTap?.(); + } + }, + listen, + ); + layer.addEventListener( + 'pointercancel', + () => { + backdropPointer = null; + }, + listen, + ); + current.untilPointersLift = watchPointers(current); + // No touch reaches the layer, or anything under it, while the source + // grows (spec:AST-094 FR35); a surface extends the hold to its own + // growth. + current.releaseGrowHold = holdPresentation(layer, { + scope: 'viewport', + until: growing.finished, + }); + return {source: sourceRect, lifted, viewport, anchor}; + }; + + // The lift layer takes no touch until the lift and the surface settle + // (spec:AST-094 FR35). The hold's shield joins the top layer after the + // surface, so it covers it too; keys and assistive technology stay live. + const holdWhileGrowing = ( + current: LiftState, + surfaceSettled: Promise, + ) => { + releaseGrowHold(current); + const until = Promise.all([current.growing.finished, surfaceSettled]); + current.releaseGrowHold = holdPresentation(current.layer, { + scope: 'viewport', + until, + }); + }; + + const presentSurface = ( + surfaceElement: HTMLElement, + pressAt?: {x: number; y: number} | null, + ) => { + const current = state; + if (current == null || !current.isSourceLifted) { + return; + } + const element = + surfaceElement.closest('[popover]') ?? surfaceElement; + endSurface(current); + const rect = element.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) { + return; + } + const box: MorphRect = { + x: rect.left, + y: rect.top, + width: rect.width, + height: rect.height, + }; + // Without a press it fades in where it rests, and a close shrinks it + // into the lifted source's center. + const press = pressAt ?? { + x: current.lifted.x + current.lifted.width / 2, + y: current.lifted.y + current.lifted.height / 2, + }; + const startWidth = Math.min( + current.options.surfaceStartWidth ?? 0, + box.width, + ); + const startHeight = (startWidth * box.height) / box.width; + const start: MorphRect = + pressAt == null + ? box + : { + x: press.x - startWidth / 2, + y: press.y - startHeight / 2, + width: startWidth, + height: startHeight, + }; + const path = lerpPath(start, box, { + box, + scale: 'uniform', + opacity: [0, 1], + }); + // The hold's shield shows before the growth writes anything, so showing + // it restyles only the shield, not the page the growth just changed. + let surfaceSettled = () => {}; + holdWhileGrowing( + current, + new Promise(resolve => { + surfaceSettled = resolve; + }), + ); + const morph = createRectMorph(element); + const presenting = morph.present(path, current.motion.surfaceIn, { + crossfadeAs: 'entrance', + }); + void presenting.finished.then(surfaceSettled, surfaceSettled); + current.surface = { + element, + morph, + path, + press: {x: press.x, y: press.y}, + presenting, + dismissing: null, + }; + }; + + const dismissSurface = (surfaceElement: HTMLElement) => { + const current = state; + if (current == null) { + return; + } + const element = + surfaceElement.closest('[popover]') ?? surfaceElement; + // A close of a surface that no longer shows (a second tap on the fading + // tint) leaves the running exit alone. + const shown = element.getBoundingClientRect(); + if (shown.width <= 0 || shown.height <= 0) { + return; + } + let surface = current.surface; + if (surface == null || surface.element !== element) { + // A surface that showed without growing: it shrinks from rest into the + // source's center. + endSurface(current); + const box: MorphRect = { + x: shown.left, + y: shown.top, + width: shown.width, + height: shown.height, + }; + const press = { + x: current.lifted.x + current.lifted.width / 2, + y: current.lifted.y + current.lifted.height / 2, + }; + const startWidth = Math.min( + current.options.surfaceStartWidth ?? 0, + box.width, + ); + const startHeight = (startWidth * box.height) / box.width; + surface = { + element, + morph: createRectMorph(element), + path: lerpPath( + { + x: press.x - startWidth / 2, + y: press.y - startHeight / 2, + width: startWidth, + height: startHeight, + }, + box, + {box, scale: 'uniform', opacity: [0, 1]}, + ), + press, + presenting: null, + dismissing: null, + }; + current.surface = surface; + } + // The layer runtime's exit copy (inert, unnamed, in the top layer where + // the surface is drawn), taken while it still shows. Without a top layer + // there is no copy, and the close is immediate. + const copy = placeLayerExitCopy(element, `${current.attribute}-exit`); + if (copy == null) { + return; + } + surface.dismissing = surface.morph.dismiss( + surface.path, + current.motion.surfaceOut, + {target: copy, crossfadeAs: 'exit'}, + ); + }; + + const drop = () => { + const current = state; + if (current == null || !current.isSourceLifted) { + return; + } + releaseGrowHold(current); + const {layer, motion, source, sourceRect, lifted} = current; + // The tint clears from what it shows now, read before its rise stops. + const tintFrom = backdropOpacity(layer, 1); + current.tint?.cancel(); + current.tint = fadeBackdrop(layer, 0, motion.clear, {from: tintFrom}); + // The source returns to its place from wherever it is now, with its + // velocity; its shadow follows it back frame for frame (the same start, + // the same velocity along the way back) and fades on its own spring. + // Under Reduce Motion both fade where they are. + // One instant for the shadow's reading and the morph's own, and the + // morph's velocity there (from the rect it presents a millisecond + // before: the morph keeps its own clock, synced to its animations'). + const at = performance.now(); + current.holdClock(at - 1); + const before = current.morph.presentedRect() ?? lifted; + current.holdClock(at); + const presented = current.morph.presentedRect() ?? lifted; + const shadowEl = current.shadow; + const shownOpacity = + Number.parseFloat( + shadowEl.ownerDocument.defaultView?.getComputedStyle(shadowEl) + .opacity ?? '', + ) || 0; + current.shadowAnimation?.cancel(); + const reducedFade = reducedMotionFade(source); + // That velocity as progress along the way back (from where it is drawn + // to the source's place), as the morph reads it. + const span = presented.width - sourceRect.width; + const widthVelocity = (presented.width - before.width) * 1000; + const backVelocity = Math.abs(span) > 1e-6 ? -widthVelocity / span : 0; + current.shadowAnimation = playShadow( + shadowEl, + shadowKeyframes( + sourceRect, + presented, + reducedFade == null ? sourceRect : presented, + reducedFade == null ? motion.drop : null, + [shownOpacity, 0], + motion.shadowOut, + backVelocity, + ), + reducedFade, + ); + const returning = current.morph.dismiss( + lerpPath(sourceRect, lifted, {box: sourceRect, scale: 'uniform'}), + motion.drop, + {target: source, crossfadeAs: 'exit'}, + ); + current.holdClock(null); + const exit = current.surface?.dismissing; + const settled = Promise.all([returning.finished, exit?.finished]); + void settled.then(() => { + if (state !== current) { + return; + } + endSurface(current); + settleSource(current); + // Under Reduce Motion the source faded out where it stood: it fades + // back in at its place. + const back = reducedMotionFade(source); + if (back != null && typeof source.animate === 'function') { + source.animate([{opacity: 0}, {opacity: 1}], { + duration: back.duration, + easing: back.easing, + }); + } + }); + // The close holds the layer: nothing reaches the page under it until the + // source is back, the surface's exit is done and every press on the + // layer has lifted. + const ended = settled.then(async () => current.untilPointersLift()); + current.releaseHold?.(); + current.releaseHold = holdPresentation(layer, { + scope: 'layer', + until: ended, + }); + void ended.then(() => { + if (state === current) { + end(current); + } + }); + }; + + return { + lift, + presentSurface, + dismissSurface, + drop, + dispose: () => { + if (state != null) { + end(state); + } + }, + isLifted: () => state?.isSourceLifted === true, + }; +} diff --git a/packages/core/src/lift/liftGeometry.test.ts b/packages/core/src/lift/liftGeometry.test.ts new file mode 100644 index 0000000000000..9ac455d682687 --- /dev/null +++ b/packages/core/src/lift/liftGeometry.test.ts @@ -0,0 +1,103 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file liftGeometry.test.ts + * @input vitest, the lift geometry + * @output Checks how far a source grows (the cap, the points on its larger + * side, the viewport's width), where it lands inside the gutter, and which + * side of it a surface takes, in either direction + * @position Unit tests of packages/core/src/lift/liftGeometry.ts; a + * surface's own numbers (UIKit's, for ContextMenu) are tested with it + */ + +import {describe, expect, it} from 'vitest'; +import { + liftedRect, + liftScale, + surfacePlacement, + type LiftViewport, +} from './liftGeometry'; + +const RULE = {maxScale: 1.15, scaleUpPoints: 26}; +const VIEWPORT: LiftViewport = { + width: 402, + height: 874, + gutter: {top: 82, bottom: 54, inline: 16}, +}; + +describe('liftScale', () => { + it('caps a small source at the rule’s largest factor', () => { + expect(liftScale(60, 60, VIEWPORT, RULE)).toBe(1.15); + }); + + it('grows a larger source by the rule’s points on its larger side', () => { + expect(liftScale(200, 120, VIEWPORT, RULE)).toBeCloseTo(226 / 200, 10); + }); + + it('shrinks a source wider than the viewport less its gutter', () => { + expect(liftScale(402, 60, VIEWPORT, RULE)).toBeCloseTo(370 / 402, 10); + }); + + it('leaves an empty source alone', () => { + expect(liftScale(0, 0, VIEWPORT, RULE)).toBe(1); + }); +}); + +describe('liftedRect', () => { + it('grows about the source’s center', () => { + const lifted = liftedRect( + {x: 101, y: 400, width: 200, height: 120}, + VIEWPORT, + RULE, + ); + expect(lifted.x + lifted.width / 2).toBeCloseTo(201, 10); + expect(lifted.y + lifted.height / 2).toBeCloseTo(460, 10); + expect(lifted.width).toBeCloseTo(226, 10); + }); + + it('moves inside the gutter on every edge', () => { + expect( + liftedRect({x: 4, y: 400, width: 60, height: 60}, VIEWPORT, RULE).x, + ).toBe(16); + const right = liftedRect( + {x: 340, y: 400, width: 60, height: 60}, + VIEWPORT, + RULE, + ); + expect(right.x + right.width).toBeCloseTo(386, 10); + expect( + liftedRect({x: 100, y: 60, width: 60, height: 60}, VIEWPORT, RULE).y, + ).toBe(82); + const bottom = liftedRect( + {x: 100, y: 800, width: 60, height: 60}, + VIEWPORT, + RULE, + ); + expect(bottom.y + bottom.height).toBeCloseTo(820, 10); + }); +}); + +describe('surfacePlacement', () => { + const middle = {x: 88, y: 368, width: 226, height: 135.67}; + + it('goes below the source, centered, where it fits above the bottom gutter', () => { + expect(surfacePlacement(middle, 200, VIEWPORT, 16)).toEqual({ + side: 'below', + alignment: 'center', + }); + }); + + it('goes above where it does not fit below', () => { + expect(surfacePlacement(middle, 400, VIEWPORT, 16).side).toBe('above'); + }); + + it('is flush with the edge the source is held against, and the sides swap in a right-to-left page', () => { + const atLeft = {...middle, x: 16}; + const atRight = {...middle, x: 386 - middle.width}; + expect(surfacePlacement(atLeft, 200, VIEWPORT, 16).alignment).toBe('start'); + expect(surfacePlacement(atRight, 200, VIEWPORT, 16).alignment).toBe('end'); + const rtl: LiftViewport = {...VIEWPORT, direction: 'rtl'}; + expect(surfacePlacement(atLeft, 200, rtl, 16).alignment).toBe('end'); + expect(surfacePlacement(atRight, 200, rtl, 16).alignment).toBe('start'); + }); +}); diff --git a/packages/core/src/lift/liftGeometry.ts b/packages/core/src/lift/liftGeometry.ts new file mode 100644 index 0000000000000..2660705ea6c0b --- /dev/null +++ b/packages/core/src/lift/liftGeometry.ts @@ -0,0 +1,149 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file liftGeometry.ts + * @input A source's box, the viewport and the layer runtime's gutter, and + * the caller's scale rule and gap + * @output Exports liftScale, liftedRect and surfacePlacement: how far a + * lifted source grows, where it lands inside the gutter, and which side of + * it a surface (a menu) takes + * @position The geometry of the lift presentation (lift.ts); internal to + * core + * + * A lifted source grows about its center by the caller's rule (UIKit's + * preview platter: up to a factor, by a number of points on its larger + * side, and never wider than the screen less the gutter), then moves inside + * the layer runtime's viewport gutter (spec:AST-059) if it crosses it. A + * surface sits a gap away: below the source when it fits above the bottom + * gutter, else above; centered on the source, or flush with the edge the + * source is held against. + * + * SYNC: When modified, update /packages/core/src/lift/liftGeometry.test.ts + */ + +import type {MorphRect} from '../motion/rectMorph'; + +/** + * The layer runtime's viewport gutter on each edge, CSS px + * (Layer/layerViewportInset.stylex.ts, spec:AST-059): the spacing step or the + * edge's safe-area inset, whichever is larger, plus the inset an app declares + * for a bar floating over that edge. + */ +export interface LiftGutter { + readonly top: number; + readonly bottom: number; + readonly inline: number; +} + +/** + * The viewport a source lifts in, CSS px, the layer runtime's gutter, and the + * page's direction (a surface's alignment is logical). + */ +export interface LiftViewport { + readonly width: number; + readonly height: number; + readonly gutter: LiftGutter; + readonly direction?: 'ltr' | 'rtl'; +} + +/** How far a lifted source grows. */ +export interface LiftScaleRule { + /** The largest factor it grows by. */ + readonly maxScale: number; + /** Below `maxScale`, it grows by this many px on its larger side. */ + readonly scaleUpPoints: number; +} + +/** Where a surface sits against the lifted source. */ +export interface SurfacePlacement { + readonly side: 'above' | 'below'; + readonly alignment: 'start' | 'center' | 'end'; +} + +/** + * The factor a `width` × `height` source grows by: up to `rule.maxScale`, by + * `rule.scaleUpPoints` on its larger side, and never wider than the viewport + * less its gutter (which can make it smaller than 1). + */ +export function liftScale( + width: number, + height: number, + viewport: LiftViewport, + rule: LiftScaleRule, +): number { + const side = Math.max(width, height); + if (side <= 0) { + return 1; + } + const fitsWidth = + width > 0 + ? (viewport.width - 2 * viewport.gutter.inline) / width + : Infinity; + return Math.min(rule.maxScale, (side + rule.scaleUpPoints) / side, fitsWidth); +} + +/** + * The lifted source's rect: `source` scaled by `liftScale` about its center, + * then moved inside the viewport's gutter if it crosses it. + */ +export function liftedRect( + source: MorphRect, + viewport: LiftViewport, + rule: LiftScaleRule, +): MorphRect { + const {gutter} = viewport; + const scale = liftScale(source.width, source.height, viewport, rule); + const width = source.width * scale; + const height = source.height * scale; + const clamp = (value: number, min: number, max: number) => + Math.min(Math.max(value, min), Math.max(min, max)); + const top = gutter.top; + const bottom = viewport.height - gutter.bottom; + return { + x: clamp( + source.x + source.width / 2 - width / 2, + gutter.inline, + viewport.width - gutter.inline - width, + ), + y: clamp(source.y + source.height / 2 - height / 2, top, bottom - height), + width, + height, + }; +} + +/** + * A surface's place: below the lifted source when `surfaceHeight` fits + * between it, `gap` and the bottom gutter, else above; centered on the + * source, or flush with the source's edge when the source is held against a + * side of the viewport. + */ +export function surfacePlacement( + lifted: MorphRect, + surfaceHeight: number, + viewport: LiftViewport, + gap: number, +): SurfacePlacement { + const {gutter} = viewport; + const bottom = viewport.height - gutter.bottom; + const side = + lifted.y + lifted.height + gap + surfaceHeight <= bottom + ? 'below' + : 'above'; + const epsilon = 0.5; + const atLeft = lifted.x <= gutter.inline + epsilon; + const atRight = + lifted.x + lifted.width >= viewport.width - gutter.inline - epsilon; + // Flush with the edge the source is held against; the alignment is + // logical, so a right-to-left page swaps the physical sides. + const isRtl = viewport.direction === 'rtl'; + const alignment = atLeft + ? isRtl + ? 'end' + : 'start' + : atRight + ? isRtl + ? 'start' + : 'end' + : 'center'; + return {side, alignment}; +} diff --git a/packages/core/src/lift/useLift.ts b/packages/core/src/lift/useLift.ts new file mode 100644 index 0000000000000..4fb6dcd254cef --- /dev/null +++ b/packages/core/src/lift/useLift.ts @@ -0,0 +1,30 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useLift.ts + * @input React + * @output Exports useLift: a component's one lift (lift.ts), ended when the + * component unmounts + * @position The React entry to the lift presentation; internal to core and + * opt-in, like the module itself + * + * SYNC: When modified, update /packages/core/src/lift/lift.test.ts + */ + +import {useEffect, useRef} from 'react'; +import {createLift, type Lift} from './lift'; + +/** + * The component's lift. It stays the same object for the component's life; + * an unmount ends whatever it has up and leaves the page as it was + * (spec:AST-094 FR24). + */ +export function useLift(): Lift { + const liftRef = useRef(null); + liftRef.current ??= createLift(); + const lift = liftRef.current; + useEffect(() => () => lift.dispose(), [lift]); + return lift; +} From a13c9b00c79adfc364b68ab50e1da1bfe44513e6 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 06:58:13 -0700 Subject: [PATCH 19/65] docs(lift): the lift's springs are the caller's, not motion roles Under main's rule (themes do not set motion roles; the touch tables register FR4's roles only), a lift's springs are its caller's own values. lift.ts's header, LiftMotion, LiftState and resolvedMotion docs and the module's README no longer say a theme retunes them. Comments only. --- packages/core/src/lift/README.md | 3 +-- packages/core/src/lift/lift.ts | 13 +++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/core/src/lift/README.md b/packages/core/src/lift/README.md index 918fdb53f7aa6..f901d5d7fe576 100644 --- a/packages/core/src/lift/README.md +++ b/packages/core/src/lift/README.md @@ -13,8 +13,7 @@ Layer stays generic. The top layer, dismissal, the presentation hold (`Layer/presentationHold.ts`) and the shared exit copy (`Layer/layerExitCopy.ts`) belong to Layer; the lift only uses them. Its motion is the rect morph's (`motion/rectMorph.ts`), and its springs, scale -rule and gap are the caller's own motion roles and constants, so a theme -retunes them where the surface declares them. +rule and gap are the caller's own. ## What a lift adds diff --git a/packages/core/src/lift/lift.ts b/packages/core/src/lift/lift.ts index e51d603df90a9..41fa54ff10a3e 100644 --- a/packages/core/src/lift/lift.ts +++ b/packages/core/src/lift/lift.ts @@ -5,8 +5,8 @@ /** * @file lift.ts * @input An element to lift (the source) and, beside it, a surface that - * grows out of the press (a menu's popover); the caller's springs (motion - * roles a theme may retune), scale rule and tint; the rect morph + * grows out of the press (a menu's popover); the caller's springs, scale + * rule and tint; the rect morph * (motion/rectMorph.ts); the layer runtime's presentation hold, exit copy, * viewport gutter and declared inset * @output Exports createLift: lift a source out of the page above a tinted @@ -97,7 +97,7 @@ import { */ const CLICK_AFTER_LIFT_MS = 350; -/** The springs of a lift; the caller's motion roles. */ +/** The springs of a lift: the caller's. */ export interface LiftMotion { /** The source grows to its lifted rect on it, and the tint fades in. */ readonly lift: SpringDescription; @@ -210,7 +210,7 @@ interface LiftedSurface { interface LiftState { readonly generation: number; readonly options: LiftOptions; - /** The springs, as the source's theme set them at the lift. */ + /** The springs, resolved where the source is at the lift. */ readonly motion: LiftMotion; readonly attribute: string; readonly source: HTMLElement; @@ -418,8 +418,9 @@ function probe( } /** - * The lift's springs as `element`'s theme sets them, read once: plain - * springs, which nothing reads from the page again. + * The lift's springs as they resolve at `element` (a spring that is a motion + * role, through its role), read once: plain springs, which nothing reads + * from the page again. */ function resolvedMotion(element: Element, motion: LiftMotion): LiftMotion { const resolve = (spring: SpringDescription): SpringDescription => ({ From b3e79dfc74f0e5b625d28ee551307673f71bfd0f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 11:36:30 -0700 Subject: [PATCH 20/65] refactor(lift): the lift holds input through the layer runtime's input hold The layer runtime's presentation hold is now the input hold (Layer/inputHold, holdInput). The lift's import, its unit test's spy and the module's docs follow the new names. Behavior is unchanged. --- packages/core/src/lift/README.md | 6 +++--- packages/core/src/lift/lift.test.ts | 22 +++++++++++----------- packages/core/src/lift/lift.ts | 14 +++++++------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/packages/core/src/lift/README.md b/packages/core/src/lift/README.md index f901d5d7fe576..1a52eaceaf9f1 100644 --- a/packages/core/src/lift/README.md +++ b/packages/core/src/lift/README.md @@ -9,8 +9,8 @@ default, and any surface that lifts uses this module, never a copy of it. Nothing here is exported from the package entry point; components import it by path. -Layer stays generic. The top layer, dismissal, the presentation hold -(`Layer/presentationHold.ts`) and the shared exit copy +Layer stays generic. The top layer, dismissal, the input hold +(`Layer/inputHold.ts`) and the shared exit copy (`Layer/layerExitCopy.ts`) belong to Layer; the lift only uses them. Its motion is the rect morph's (`motion/rectMorph.ts`), and its springs, scale rule and gap are the caller's own. @@ -26,7 +26,7 @@ is the tint); the shadow, a box in the layer that follows the trigger on a rect morph of its own (an animated `::backdrop` of the trigger would restyle and lay out the page on every frame); an empty box at the lifted rect for the surface to be placed against (anchor positioning follows transforms, so -a box inside the trigger would move with it); and the placeholder. The presentation hold's shield joins while the lift grows and +a box inside the trigger would move with it); and the placeholder. The input hold's shield joins while the lift grows and while it closes: never more than five (`spec:AST-017` FR60, DEC-29). The exit copy the surface shrinks on is the layer runtime's transient copy. At rest there is nothing. diff --git a/packages/core/src/lift/lift.test.ts b/packages/core/src/lift/lift.test.ts index c31cca90e253b..ba936e10847ec 100644 --- a/packages/core/src/lift/lift.test.ts +++ b/packages/core/src/lift/lift.test.ts @@ -3,7 +3,7 @@ /** * @file lift.test.ts * @input vitest (jsdom), the lift, stand-ins for the popover API and for - * layout (jsdom has neither) and a spy on the presentation hold + * layout (jsdom has neither) and a spy on the input hold * @output Checks the lift's bookkeeping in the page: while up it adds the * layer and one placeholder whatever the source holds, and nothing at * rest; the source keeps its place among its siblings; a drop or an @@ -16,15 +16,15 @@ */ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import * as presentationHold from '../Layer/presentationHold'; +import * as inputHold from '../Layer/inputHold'; import {createLift, type LiftOptions} from './lift'; -vi.mock('../Layer/presentationHold', async importOriginal => ({ - ...(await importOriginal()), - holdPresentation: vi.fn(() => () => {}), +vi.mock('../Layer/inputHold', async importOriginal => ({ + ...(await importOriginal()), + holdInput: vi.fn(() => () => {}), })); -const {holdPresentation} = presentationHold; +const {holdInput} = inputHold; const SPRING = {response: 0.3, dampingRatio: 1}; @@ -171,7 +171,7 @@ beforeEach(() => { realRemove(type, listener, opts); }, ); - vi.mocked(holdPresentation).mockClear(); + vi.mocked(holdInput).mockClear(); }); afterEach(() => { @@ -362,21 +362,21 @@ describe('lift', () => { const lift = createLift(); lift.lift(source, options()); const layer = document.querySelector('[data-test-lift]'); - expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + expect(vi.mocked(holdInput)).toHaveBeenLastCalledWith(layer, { scope: 'viewport', until: expect.any(Promise), }); - vi.mocked(holdPresentation).mockClear(); + vi.mocked(holdInput).mockClear(); lift.presentSurface( menu.querySelector('[role="menu"]') as HTMLElement, {x: 180, y: 330}, ); - expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + expect(vi.mocked(holdInput)).toHaveBeenLastCalledWith(layer, { scope: 'viewport', until: expect.any(Promise), }); lift.drop(); - expect(vi.mocked(holdPresentation)).toHaveBeenLastCalledWith(layer, { + expect(vi.mocked(holdInput)).toHaveBeenLastCalledWith(layer, { scope: 'layer', until: expect.any(Promise), }); diff --git a/packages/core/src/lift/lift.ts b/packages/core/src/lift/lift.ts index 41fa54ff10a3e..171ee4b0d6e00 100644 --- a/packages/core/src/lift/lift.ts +++ b/packages/core/src/lift/lift.ts @@ -7,7 +7,7 @@ * @input An element to lift (the source) and, beside it, a surface that * grows out of the press (a menu's popover); the caller's springs, scale * rule and tint; the rect morph - * (motion/rectMorph.ts); the layer runtime's presentation hold, exit copy, + * (motion/rectMorph.ts); the layer runtime's input hold, exit copy, * viewport gutter and declared inset * @output Exports createLift: lift a source out of the page above a tinted * backdrop, grow a surface out of the press beside it, shrink the surface @@ -15,7 +15,7 @@ * @position The one lift-from-trigger presentation, internal to core and * opt-in: only a surface that chooses it uses it (ContextMenu's touch * invocation today). Layer stays generic: the top layer, dismissal, the - * presentation hold and the shared exit copy are its; this module only + * input hold and the shared exit copy are its; this module only * uses them * * UIKit's context menu lifts the long-pressed view out of the page: it grows @@ -52,7 +52,7 @@ * its own along the same path; the tint as a spring-sampled Web Animation of * the layer's `::backdrop`. A tap or * a drag that lands while the lift and the surface grow reaches nothing - * (the presentation hold, FR35); the close holds the layer until the source + * (the input hold, FR35); the close holds the layer until the source * is back, the surface's exit is done and every press on the layer has * lifted. Its timers and document listeners end with it (FR24). Reduce * Motion is the animator's (design:reduced-motion): opacity only. @@ -66,7 +66,7 @@ import type {LayerInset} from '../Layer/LayerContext'; import {placeLayerExitCopy} from '../Layer/layerExitCopy'; import {layerInsetProperties} from '../Layer/layerInset'; import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; -import {holdPresentation} from '../Layer/presentationHold'; +import {holdInput} from '../Layer/inputHold'; import type {MotionHandle} from '../motion/animator'; import {progressCurve} from '../motion/progress'; import { @@ -1009,7 +1009,7 @@ export function createLift(): Lift { // No touch reaches the layer, or anything under it, while the source // grows (spec:AST-094 FR35); a surface extends the hold to its own // growth. - current.releaseGrowHold = holdPresentation(layer, { + current.releaseGrowHold = holdInput(layer, { scope: 'viewport', until: growing.finished, }); @@ -1025,7 +1025,7 @@ export function createLift(): Lift { ) => { releaseGrowHold(current); const until = Promise.all([current.growing.finished, surfaceSettled]); - current.releaseGrowHold = holdPresentation(current.layer, { + current.releaseGrowHold = holdInput(current.layer, { scope: 'viewport', until, }); @@ -1245,7 +1245,7 @@ export function createLift(): Lift { // layer has lifted. const ended = settled.then(async () => current.untilPointersLift()); current.releaseHold?.(); - current.releaseHold = holdPresentation(layer, { + current.releaseHold = holdInput(layer, { scope: 'layer', until: ended, }); From 68c64c179a6acb909d14e79e6e93f16aa7c4c4ec Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 12:33:01 -0700 Subject: [PATCH 21/65] refactor(liftFromTrigger): the lift-from-trigger module takes its record's name architecture:layer-runtime INV15 calls it the lift-from-trigger module, and in spec:AST-094 a bare "lift" is the finger leaving the screen. The module moves to packages/core/src/liftFromTrigger/ and its exports take the name: createLiftFromTrigger, useLiftFromTrigger, LiftFromTrigger{,Motion,Options,Result}, and the geometry's LiftFromTrigger{Gutter,Viewport,ScaleRule}, liftFromTriggerScale and liftFromTriggerRect. Files, headers, SYNC paths and tests follow. Behavior is unchanged. --- .../src/{lift => liftFromTrigger}/README.md | 14 ++--- .../__tests__/liftFromTrigger.fixture.ts} | 16 +++--- ...ftFromTrigger.interaction.browser.spec.ts} | 14 ++--- .../liftFromTrigger.test.ts} | 33 +++++++----- .../liftFromTrigger.ts} | 54 ++++++++++--------- .../liftFromTriggerGeometry.test.ts} | 49 ++++++++++------- .../liftFromTriggerGeometry.ts} | 39 ++++++++------ .../useLiftFromTrigger.ts} | 14 ++--- 8 files changed, 132 insertions(+), 101 deletions(-) rename packages/core/src/{lift => liftFromTrigger}/README.md (72%) rename packages/core/src/{lift/__tests__/lift.fixture.ts => liftFromTrigger/__tests__/liftFromTrigger.fixture.ts} (90%) rename packages/core/src/{lift/__tests__/lift.interaction.browser.spec.ts => liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts} (97%) rename packages/core/src/{lift/lift.test.ts => liftFromTrigger/liftFromTrigger.test.ts} (95%) rename packages/core/src/{lift/lift.ts => liftFromTrigger/liftFromTrigger.ts} (97%) rename packages/core/src/{lift/liftGeometry.test.ts => liftFromTrigger/liftFromTriggerGeometry.test.ts} (69%) rename packages/core/src/{lift/liftGeometry.ts => liftFromTrigger/liftFromTriggerGeometry.ts} (81%) rename packages/core/src/{lift/useLift.ts => liftFromTrigger/useLiftFromTrigger.ts} (54%) diff --git a/packages/core/src/lift/README.md b/packages/core/src/liftFromTrigger/README.md similarity index 72% rename from packages/core/src/lift/README.md rename to packages/core/src/liftFromTrigger/README.md index 1a52eaceaf9f1..92e02b89072cb 100644 --- a/packages/core/src/lift/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -1,4 +1,4 @@ -# Lift +# LiftFromTrigger The one lift-from-trigger presentation, internal to core and opt-in. A surface that chooses it (ContextMenu's touch invocation today) lifts its @@ -45,9 +45,9 @@ document listeners end with it, and an unmount ends everything at once ## Files -| File | What it is | -| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `lift.ts` | `createLift`: lift a trigger, grow and close a surface beside it, drop, end. | -| `useLift.ts` | A component's one lift, ended when it unmounts. | -| `liftGeometry.ts` | How far the trigger grows, where it lands inside the layer runtime's gutter, which side the surface takes. | -| `__tests__/lift.interaction.browser.spec.ts` | Browser proofs (Chromium and WebKit): the top layer, the placeholder, the properties that move, counts, leaks. | +| File | What it is | +| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `liftFromTrigger.ts` | `createLiftFromTrigger`: lift a trigger, grow and close a surface beside it, drop, end. | +| `useLiftFromTrigger.ts` | A component's one lift, ended when it unmounts. | +| `liftFromTriggerGeometry.ts` | How far the trigger grows, where it lands inside the layer runtime's gutter, which side the surface takes. | +| `__tests__/liftFromTrigger.interaction.browser.spec.ts` | Browser proofs (Chromium and WebKit): the top layer, the placeholder, the properties that move, counts, leaks. | diff --git a/packages/core/src/lift/__tests__/lift.fixture.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts similarity index 90% rename from packages/core/src/lift/__tests__/lift.fixture.ts rename to packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts index 17465ff30ac50..38bf875ef0681 100644 --- a/packages/core/src/lift/__tests__/lift.fixture.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts @@ -1,17 +1,21 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. /** - * @file lift.fixture.ts + * @file liftFromTrigger.fixture.ts * @input Nothing: bundled by esbuild and injected into a blank page * @output A page with a list of rows inside a clipping, transformed panel * (the first row rounded by `:first-child`, the second holding twelve * elements), a menu popover beside it, and `window.__lift`: lift a row, * grow and close the menu, drop, end, and the backdrop taps and the * clicks the page received - * @position Browser fixture of lift.interaction.browser.spec.ts; test-only + * @position Browser fixture of liftFromTrigger.interaction.browser.spec.ts; test-only */ -import {createLift, type LiftOptions, type LiftResult} from '../lift'; +import { + createLiftFromTrigger, + type LiftFromTriggerOptions, + type LiftFromTriggerResult, +} from '../liftFromTrigger'; interface LiftLog { backdropTaps: number; @@ -21,7 +25,7 @@ interface LiftLog { /** The page's handle on its lift. */ export interface LiftFixture { log: LiftLog; - lift: (id: string, springResponse?: number) => LiftResult | null; + lift: (id: string, springResponse?: number) => LiftFromTriggerResult | null; presentMenu: (press: {x: number; y: number} | null) => void; dismissMenu: () => void; closeMenu: () => void; @@ -85,9 +89,9 @@ document.addEventListener( true, ); -const lift = createLift(); +const lift = createLiftFromTrigger(); -function options(response: number): LiftOptions { +function options(response: number): LiftFromTriggerOptions { const spring = {response, dampingRatio: 0.9}; return { motion: { diff --git a/packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts similarity index 97% rename from packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts rename to packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 2281de2382e27..5da38b0fa1823 100644 --- a/packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -1,9 +1,9 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. /** - * @file lift.interaction.browser.spec.ts + * @file liftFromTrigger.interaction.browser.spec.ts * @input The lift bundled with esbuild onto a blank fixture page - * (lift.fixture.ts): a list of rows in a clipping, transformed panel and a + * (liftFromTrigger.fixture.ts): a list of rows in a clipping, transformed panel and a * menu popover; Chromium and WebKit * @output Proof in real engines that a row lifts itself into the top layer * at its lifted rect while one placeholder holds its spot (nothing else @@ -18,7 +18,7 @@ * (AST-017 FR60); that repeated lifts leave no node or listener behind; * that a tap while it grows reaches nothing (FR35) and one on the backdrop * afterwards is the backdrop tap - * @position Browser proof for lift.ts, run by `pnpm test:interaction`; jsdom + * @position Browser proof for liftFromTrigger.ts, run by `pnpm test:interaction`; jsdom * has no layout, no top layer and no animations */ @@ -27,7 +27,7 @@ import {fileURLToPath} from 'node:url'; import {expect, test, type Page} from '@playwright/test'; import {build, type Plugin} from 'esbuild'; // The page's `window.__lift`. -import type {LiftFixture} from './lift.fixture'; +import type {LiftFixture} from './liftFromTrigger.fixture'; // The layer runtime's gutter is a `stylex.defineConsts` table: static values // the StyleX compiler puts in place of the call. Unbundled by that compiler, @@ -54,7 +54,7 @@ test.beforeAll(async () => { entryPoints: [ path.join( path.dirname(fileURLToPath(import.meta.url)), - 'lift.fixture.ts', + 'liftFromTrigger.fixture.ts', ), ], bundle: true, @@ -77,7 +77,7 @@ async function open(page: Page) { } type Box = [number, number, number, number]; -type LiftResult = NonNullable>; +type LiftFromTriggerResult = NonNullable>; function expectBox(actual: Box, expected: Box, tolerance = 0.5) { for (let i = 0; i < 4; i++) { @@ -124,7 +124,7 @@ test('a row lifts itself into the top layer at its lifted rect while one placeho expect(after.isOpen).toBe(true); // Grown by 26 px on its larger side, about its center: wider than the // clipping panel, and drawn whole. - const lifted: LiftResult['lifted'] = result?.lifted ?? { + const lifted: LiftFromTriggerResult['lifted'] = result?.lifted ?? { x: 0, y: 0, width: 0, diff --git a/packages/core/src/lift/lift.test.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts similarity index 95% rename from packages/core/src/lift/lift.test.ts rename to packages/core/src/liftFromTrigger/liftFromTrigger.test.ts index ba936e10847ec..f4c60f4c37389 100644 --- a/packages/core/src/lift/lift.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. /** - * @file lift.test.ts + * @file liftFromTrigger.test.ts * @input vitest (jsdom), the lift, stand-ins for the popover API and for * layout (jsdom has neither) and a spy on the input hold * @output Checks the lift's bookkeeping in the page: while up it adds the @@ -12,12 +12,15 @@ * it over repeated lifts; the gutter it reads; the holds it takes; taps on * its backdrop * @position Testing; the motion, the top layer and the counts in real - * engines are proven in __tests__/lift.interaction.browser.spec.ts + * engines are proven in __tests__/liftFromTrigger.interaction.browser.spec.ts */ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import * as inputHold from '../Layer/inputHold'; -import {createLift, type LiftOptions} from './lift'; +import { + createLiftFromTrigger, + type LiftFromTriggerOptions, +} from './liftFromTrigger'; vi.mock('../Layer/inputHold', async importOriginal => ({ ...(await importOriginal()), @@ -28,7 +31,9 @@ const {holdInput} = inputHold; const SPRING = {response: 0.3, dampingRatio: 1}; -function options(overrides: Partial = {}): LiftOptions { +function options( + overrides: Partial = {}, +): LiftFromTriggerOptions { return { motion: { lift: SPRING, @@ -194,7 +199,7 @@ describe('lift', () => { it('adds the layer, its shadow and anchor, and one placeholder while lifted, whatever the source holds; the source keeps its place among its siblings', () => { const {source, before} = renderList(); const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); const result = lift.lift(source, options()); expect(result).not.toBeNull(); // 13 elements lifted (the row and its 12), 4 added. @@ -262,7 +267,7 @@ describe('lift', () => { return resolved; }, ); - const lift = createLift(); + const lift = createLiftFromTrigger(); const result = lift.lift(source, options({inset: {blockEnd: 56}})); expect(declaredInset).toBe('56px'); expect(result?.viewport.gutter).toEqual({top: 47, bottom: 34, inline: 16}); @@ -273,7 +278,7 @@ describe('lift', () => { it('a drop puts back exactly what the source had inline, and takes the placeholder and the layer away', async () => { const {source} = renderList(); const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options()); lift.drop(); await vi.runAllTimersAsync(); @@ -287,7 +292,7 @@ describe('lift', () => { it('an unmount mid-lift ends it at once: no element, document listener or timer left', () => { const {source} = renderList(); const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options()); lift.dispose(); expectInlineAsBefore(source); @@ -300,7 +305,7 @@ describe('lift', () => { it('an unmount while the close waits for a press on the layer to lift leaves nothing behind either', async () => { const {source} = renderList(); const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options()); const layer = document.body.lastElementChild as HTMLElement; // A finger down on the layer, never lifted: the close waits for it. @@ -319,7 +324,7 @@ describe('lift', () => { it('twenty lifts and drops leave the page, the document listeners and the timers as they were (no leaks)', async () => { const {source} = renderList(); const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); for (let i = 0; i < 20; i++) { lift.lift(source, options()); lift.drop(); @@ -336,7 +341,7 @@ describe('lift', () => { const html = document.body.innerHTML; // @ts-expect-error: a browser without the popover API. HTMLElement.prototype.showPopover = undefined; - const lift = createLift(); + const lift = createLiftFromTrigger(); expect(lift.lift(source, options())).toBeNull(); expect(document.body.innerHTML).toBe(html); }); @@ -345,7 +350,7 @@ describe('lift', () => { const {source} = renderList(); source.style.position = 'absolute'; const rest = count(); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options()); expect(count()).toBe(rest + 3); lift.dispose(); @@ -359,7 +364,7 @@ describe('lift', () => { ); const menu = document.getElementById('menu') as HTMLElement; place(menu, 40, 380, 250, 200); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options()); const layer = document.querySelector('[data-test-lift]'); expect(vi.mocked(holdInput)).toHaveBeenLastCalledWith(layer, { @@ -387,7 +392,7 @@ describe('lift', () => { it('a press that went down and lifted on the layer is a backdrop tap; one that came from elsewhere is not', () => { const {source} = renderList(); const onBackdropTap = vi.fn(); - const lift = createLift(); + const lift = createLiftFromTrigger(); lift.lift(source, options({onBackdropTap})); const layer = document.body.lastElementChild as HTMLElement; const pointer = (type: string, pointerId: number) => { diff --git a/packages/core/src/lift/lift.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts similarity index 97% rename from packages/core/src/lift/lift.ts rename to packages/core/src/liftFromTrigger/liftFromTrigger.ts index 171ee4b0d6e00..c9b2853d3ed9c 100644 --- a/packages/core/src/lift/lift.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -3,13 +3,13 @@ 'use client'; /** - * @file lift.ts + * @file liftFromTrigger.ts * @input An element to lift (the source) and, beside it, a surface that * grows out of the press (a menu's popover); the caller's springs, scale * rule and tint; the rect morph * (motion/rectMorph.ts); the layer runtime's input hold, exit copy, * viewport gutter and declared inset - * @output Exports createLift: lift a source out of the page above a tinted + * @output Exports createLiftFromTrigger: lift a source out of the page above a tinted * backdrop, grow a surface out of the press beside it, shrink the surface * back into the press, and return the source to its place * @position The one lift-from-trigger presentation, internal to core and @@ -58,8 +58,8 @@ * Motion is the animator's (design:reduced-motion): opacity only. * * SYNC: When modified, update: - * - /packages/core/src/lift/lift.test.ts - * - /packages/core/src/lift/__tests__/lift.interaction.browser.spec.ts + * - /packages/core/src/liftFromTrigger/liftFromTrigger.test.ts + * - /packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts */ import type {LayerInset} from '../Layer/LayerContext'; @@ -85,10 +85,10 @@ import { type SpringDescription, } from '../motion/spring'; import { - liftedRect, - type LiftScaleRule, - type LiftViewport, -} from './liftGeometry'; + liftFromTriggerRect, + type LiftFromTriggerScaleRule, + type LiftFromTriggerViewport, +} from './liftFromTriggerGeometry'; /** * How long the layer waits, once the last pointer that went down on it has @@ -98,7 +98,7 @@ import { const CLICK_AFTER_LIFT_MS = 350; /** The springs of a lift: the caller's. */ -export interface LiftMotion { +export interface LiftFromTriggerMotion { /** The source grows to its lifted rect on it, and the tint fades in. */ readonly lift: SpringDescription; /** The source returns to its place on it. */ @@ -115,10 +115,10 @@ export interface LiftMotion { readonly surfaceOut: SpringDescription; } -export interface LiftOptions { - readonly motion: LiftMotion; +export interface LiftFromTriggerOptions { + readonly motion: LiftFromTriggerMotion; /** How far the source grows. */ - readonly scale: LiftScaleRule; + readonly scale: LiftFromTriggerScaleRule; /** * The width a surface grows out of, centered on the press (its height * keeps the surface's aspect); a point by default. @@ -152,13 +152,13 @@ export interface LiftOptions { } /** Where a lift landed. */ -export interface LiftResult { +export interface LiftFromTriggerResult { /** The source's box as laid out, viewport px. */ readonly source: MorphRect; /** The rect it lands on. */ readonly lifted: MorphRect; /** The viewport and the layer runtime's gutter it lifted in. */ - readonly viewport: LiftViewport; + readonly viewport: LiftFromTriggerViewport; /** * An empty box at the lifted rect, in the layer: what a surface is placed * against (an anchor inside the source would move with the source's @@ -167,12 +167,15 @@ export interface LiftResult { readonly anchor: HTMLElement; } -export interface Lift { +export interface LiftFromTrigger { /** * Lifts `source`: returns where it lands, or null without the popover API * (nothing changes then). A lift already up ends at once. */ - lift(source: HTMLElement, options: LiftOptions): LiftResult | null; + lift( + source: HTMLElement, + options: LiftFromTriggerOptions, + ): LiftFromTriggerResult | null; /** * Grows `surface` (a popover laid out at rest, or an element inside one) * out of `press` (client px) into its box, or, without a press, fades it @@ -209,9 +212,9 @@ interface LiftedSurface { interface LiftState { readonly generation: number; - readonly options: LiftOptions; + readonly options: LiftFromTriggerOptions; /** The springs, resolved where the source is at the lift. */ - readonly motion: LiftMotion; + readonly motion: LiftFromTriggerMotion; readonly attribute: string; readonly source: HTMLElement; readonly sourceRect: MorphRect; @@ -422,7 +425,10 @@ function probe( * role, through its role), read once: plain springs, which nothing reads * from the page again. */ -function resolvedMotion(element: Element, motion: LiftMotion): LiftMotion { +function resolvedMotion( + element: Element, + motion: LiftFromTriggerMotion, +): LiftFromTriggerMotion { const resolve = (spring: SpringDescription): SpringDescription => ({ ...resolveMotion(element, spring), }); @@ -591,7 +597,7 @@ const KEPT_PROPERTIES = [ ] as const; /** Creates a lift; one per component that offers it. */ -export function createLift(): Lift { +export function createLiftFromTrigger(): LiftFromTrigger { let state: LiftState | null = null; let generation = 0; @@ -733,8 +739,8 @@ export function createLift(): Lift { const lift = ( source: HTMLElement, - options: LiftOptions, - ): LiftResult | null => { + options: LiftFromTriggerOptions, + ): LiftFromTriggerResult | null => { if (state != null) { end(state); } @@ -801,7 +807,7 @@ export function createLift(): Lift { }); const tint = probed['background-color']; const shadow = probed['box-shadow']; - const viewport: LiftViewport = { + const viewport: LiftFromTriggerViewport = { width: doc.documentElement.clientWidth || view?.innerWidth || 0, height: view?.innerHeight ?? doc.documentElement.clientHeight, gutter: { @@ -811,7 +817,7 @@ export function createLift(): Lift { }, direction, }; - const lifted = liftedRect(sourceRect, viewport, options.scale); + const lifted = liftFromTriggerRect(sourceRect, viewport, options.scale); // Writes from here on. options.release?.(); const layer = createLayer(doc, attribute); diff --git a/packages/core/src/lift/liftGeometry.test.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts similarity index 69% rename from packages/core/src/lift/liftGeometry.test.ts rename to packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts index 9ac455d682687..b1101df78cf22 100644 --- a/packages/core/src/lift/liftGeometry.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts @@ -1,51 +1,57 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. /** - * @file liftGeometry.test.ts + * @file liftFromTriggerGeometry.test.ts * @input vitest, the lift geometry * @output Checks how far a source grows (the cap, the points on its larger * side, the viewport's width), where it lands inside the gutter, and which * side of it a surface takes, in either direction - * @position Unit tests of packages/core/src/lift/liftGeometry.ts; a + * @position Unit tests of packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts; a * surface's own numbers (UIKit's, for ContextMenu) are tested with it */ import {describe, expect, it} from 'vitest'; import { - liftedRect, - liftScale, + liftFromTriggerRect, + liftFromTriggerScale, surfacePlacement, - type LiftViewport, -} from './liftGeometry'; + type LiftFromTriggerViewport, +} from './liftFromTriggerGeometry'; const RULE = {maxScale: 1.15, scaleUpPoints: 26}; -const VIEWPORT: LiftViewport = { +const VIEWPORT: LiftFromTriggerViewport = { width: 402, height: 874, gutter: {top: 82, bottom: 54, inline: 16}, }; -describe('liftScale', () => { +describe('liftFromTriggerScale', () => { it('caps a small source at the rule’s largest factor', () => { - expect(liftScale(60, 60, VIEWPORT, RULE)).toBe(1.15); + expect(liftFromTriggerScale(60, 60, VIEWPORT, RULE)).toBe(1.15); }); it('grows a larger source by the rule’s points on its larger side', () => { - expect(liftScale(200, 120, VIEWPORT, RULE)).toBeCloseTo(226 / 200, 10); + expect(liftFromTriggerScale(200, 120, VIEWPORT, RULE)).toBeCloseTo( + 226 / 200, + 10, + ); }); it('shrinks a source wider than the viewport less its gutter', () => { - expect(liftScale(402, 60, VIEWPORT, RULE)).toBeCloseTo(370 / 402, 10); + expect(liftFromTriggerScale(402, 60, VIEWPORT, RULE)).toBeCloseTo( + 370 / 402, + 10, + ); }); it('leaves an empty source alone', () => { - expect(liftScale(0, 0, VIEWPORT, RULE)).toBe(1); + expect(liftFromTriggerScale(0, 0, VIEWPORT, RULE)).toBe(1); }); }); -describe('liftedRect', () => { +describe('liftFromTriggerRect', () => { it('grows about the source’s center', () => { - const lifted = liftedRect( + const lifted = liftFromTriggerRect( {x: 101, y: 400, width: 200, height: 120}, VIEWPORT, RULE, @@ -57,18 +63,23 @@ describe('liftedRect', () => { it('moves inside the gutter on every edge', () => { expect( - liftedRect({x: 4, y: 400, width: 60, height: 60}, VIEWPORT, RULE).x, + liftFromTriggerRect({x: 4, y: 400, width: 60, height: 60}, VIEWPORT, RULE) + .x, ).toBe(16); - const right = liftedRect( + const right = liftFromTriggerRect( {x: 340, y: 400, width: 60, height: 60}, VIEWPORT, RULE, ); expect(right.x + right.width).toBeCloseTo(386, 10); expect( - liftedRect({x: 100, y: 60, width: 60, height: 60}, VIEWPORT, RULE).y, + liftFromTriggerRect( + {x: 100, y: 60, width: 60, height: 60}, + VIEWPORT, + RULE, + ).y, ).toBe(82); - const bottom = liftedRect( + const bottom = liftFromTriggerRect( {x: 100, y: 800, width: 60, height: 60}, VIEWPORT, RULE, @@ -96,7 +107,7 @@ describe('surfacePlacement', () => { const atRight = {...middle, x: 386 - middle.width}; expect(surfacePlacement(atLeft, 200, VIEWPORT, 16).alignment).toBe('start'); expect(surfacePlacement(atRight, 200, VIEWPORT, 16).alignment).toBe('end'); - const rtl: LiftViewport = {...VIEWPORT, direction: 'rtl'}; + const rtl: LiftFromTriggerViewport = {...VIEWPORT, direction: 'rtl'}; expect(surfacePlacement(atLeft, 200, rtl, 16).alignment).toBe('end'); expect(surfacePlacement(atRight, 200, rtl, 16).alignment).toBe('start'); }); diff --git a/packages/core/src/lift/liftGeometry.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts similarity index 81% rename from packages/core/src/lift/liftGeometry.ts rename to packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts index 2660705ea6c0b..a2c603b7c18c8 100644 --- a/packages/core/src/lift/liftGeometry.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts @@ -1,13 +1,13 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. /** - * @file liftGeometry.ts + * @file liftFromTriggerGeometry.ts * @input A source's box, the viewport and the layer runtime's gutter, and * the caller's scale rule and gap - * @output Exports liftScale, liftedRect and surfacePlacement: how far a + * @output Exports liftFromTriggerScale, liftFromTriggerRect and surfacePlacement: how far a * lifted source grows, where it lands inside the gutter, and which side of * it a surface (a menu) takes - * @position The geometry of the lift presentation (lift.ts); internal to + * @position The geometry of the lift presentation (liftFromTrigger.ts); internal to * core * * A lifted source grows about its center by the caller's rule (UIKit's @@ -18,7 +18,7 @@ * gutter, else above; centered on the source, or flush with the edge the * source is held against. * - * SYNC: When modified, update /packages/core/src/lift/liftGeometry.test.ts + * SYNC: When modified, update /packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts */ import type {MorphRect} from '../motion/rectMorph'; @@ -29,7 +29,7 @@ import type {MorphRect} from '../motion/rectMorph'; * edge's safe-area inset, whichever is larger, plus the inset an app declares * for a bar floating over that edge. */ -export interface LiftGutter { +export interface LiftFromTriggerGutter { readonly top: number; readonly bottom: number; readonly inline: number; @@ -39,15 +39,15 @@ export interface LiftGutter { * The viewport a source lifts in, CSS px, the layer runtime's gutter, and the * page's direction (a surface's alignment is logical). */ -export interface LiftViewport { +export interface LiftFromTriggerViewport { readonly width: number; readonly height: number; - readonly gutter: LiftGutter; + readonly gutter: LiftFromTriggerGutter; readonly direction?: 'ltr' | 'rtl'; } /** How far a lifted source grows. */ -export interface LiftScaleRule { +export interface LiftFromTriggerScaleRule { /** The largest factor it grows by. */ readonly maxScale: number; /** Below `maxScale`, it grows by this many px on its larger side. */ @@ -65,11 +65,11 @@ export interface SurfacePlacement { * `rule.scaleUpPoints` on its larger side, and never wider than the viewport * less its gutter (which can make it smaller than 1). */ -export function liftScale( +export function liftFromTriggerScale( width: number, height: number, - viewport: LiftViewport, - rule: LiftScaleRule, + viewport: LiftFromTriggerViewport, + rule: LiftFromTriggerScaleRule, ): number { const side = Math.max(width, height); if (side <= 0) { @@ -83,16 +83,21 @@ export function liftScale( } /** - * The lifted source's rect: `source` scaled by `liftScale` about its center, + * The lifted source's rect: `source` scaled by `liftFromTriggerScale` about its center, * then moved inside the viewport's gutter if it crosses it. */ -export function liftedRect( +export function liftFromTriggerRect( source: MorphRect, - viewport: LiftViewport, - rule: LiftScaleRule, + viewport: LiftFromTriggerViewport, + rule: LiftFromTriggerScaleRule, ): MorphRect { const {gutter} = viewport; - const scale = liftScale(source.width, source.height, viewport, rule); + const scale = liftFromTriggerScale( + source.width, + source.height, + viewport, + rule, + ); const width = source.width * scale; const height = source.height * scale; const clamp = (value: number, min: number, max: number) => @@ -120,7 +125,7 @@ export function liftedRect( export function surfacePlacement( lifted: MorphRect, surfaceHeight: number, - viewport: LiftViewport, + viewport: LiftFromTriggerViewport, gap: number, ): SurfacePlacement { const {gutter} = viewport; diff --git a/packages/core/src/lift/useLift.ts b/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts similarity index 54% rename from packages/core/src/lift/useLift.ts rename to packages/core/src/liftFromTrigger/useLiftFromTrigger.ts index 4fb6dcd254cef..f69d3a40a2b0f 100644 --- a/packages/core/src/lift/useLift.ts +++ b/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts @@ -3,27 +3,27 @@ 'use client'; /** - * @file useLift.ts + * @file useLiftFromTrigger.ts * @input React - * @output Exports useLift: a component's one lift (lift.ts), ended when the + * @output Exports useLiftFromTrigger: a component's one lift (liftFromTrigger.ts), ended when the * component unmounts * @position The React entry to the lift presentation; internal to core and * opt-in, like the module itself * - * SYNC: When modified, update /packages/core/src/lift/lift.test.ts + * SYNC: When modified, update /packages/core/src/liftFromTrigger/liftFromTrigger.test.ts */ import {useEffect, useRef} from 'react'; -import {createLift, type Lift} from './lift'; +import {createLiftFromTrigger, type LiftFromTrigger} from './liftFromTrigger'; /** * The component's lift. It stays the same object for the component's life; * an unmount ends whatever it has up and leaves the page as it was * (spec:AST-094 FR24). */ -export function useLift(): Lift { - const liftRef = useRef(null); - liftRef.current ??= createLift(); +export function useLiftFromTrigger(): LiftFromTrigger { + const liftRef = useRef(null); + liftRef.current ??= createLiftFromTrigger(); const lift = liftRef.current; useEffect(() => () => lift.dispose(), [lift]); return lift; From d2c974ea46d4e70e89e1f5821b98ced7a28450d4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 22:14:13 -0700 Subject: [PATCH 22/65] test(liftFromTrigger): a lifted list item leaves its list valid and the numbers after it as they were A lifted row's spot was held by a span, so a list held a span among its items and an ordered list numbered the items after it one higher while the row was lifted. Two browser proofs, red on the span: every child of the list is an li while lifted, at the row's size whatever the page styles an li with, and a later item's marker paints the same. --- ...iftFromTrigger.interaction.browser.spec.ts | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 5da38b0fa1823..c307c536d1366 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -142,6 +142,109 @@ test('a row lifts itself into the top layer at its lifted rect while one placeho await page.evaluate(() => window.__lift.dispose()); }); +test('a lifted list item leaves its list valid: an li holds its spot, so the list keeps only li children, at the item\u2019s size whatever the page styles an li with', async ({ + page, +}) => { + await open(page); + // A rule that would make any other li taller than the row it stands for. + await page.addStyleTag({ + content: 'li:not([id]) { min-height: 100px; padding: 40px 0; }', + }); + const row2 = await page.evaluate(() => { + const r = document.getElementById('row2')?.getBoundingClientRect(); + return r == null ? null : {height: r.height}; + }); + const row3Before = await page.evaluate( + () => document.getElementById('row3')?.getBoundingClientRect().top ?? -1, + ); + await page.evaluate(() => window.__lift.lift('row2', 0.2)); + await page.waitForTimeout(400); + const read = await page.evaluate(() => { + const list = document.getElementById('list'); + const placeholder = document.querySelector('[data-lift-placeholder]'); + return { + children: [...(list?.children ?? [])].map(child => child.localName), + placeholder: + placeholder == null + ? null + : { + tag: placeholder.localName, + parent: placeholder.parentElement?.id ?? null, + hidden: placeholder.getAttribute('aria-hidden'), + height: placeholder.getBoundingClientRect().height, + }, + row3: document.getElementById('row3')?.getBoundingClientRect().top ?? -1, + }; + }); + const detail = JSON.stringify(read); + expect(read.children, detail).toEqual(['li', 'li', 'li', 'li', 'li']); + expect(read.placeholder, detail).toEqual({ + tag: 'li', + parent: 'list', + hidden: 'true', + height: row2?.height ?? -1, + }); + expect(read.row3, detail).toBe(row3Before); + await page.evaluate(() => window.__lift.dispose()); +}); + +test('a lifted item of an ordered list leaves the numbers of the items after it as they were', async ({ + page, +}) => { + await open(page); + // An ordered list with its markers outside, and no tint and no shadow: a + // later item's marker paints the same while an item is lifted unless its + // number changes. + const clip = await page.evaluate(() => { + const root = document.documentElement.style; + root.setProperty('--color-overlay', 'transparent'); + root.setProperty('--shadow-high', 'none'); + const panel = document.querySelector('.panel'); + if (panel != null) { + panel.style.display = 'none'; + } + const holder = document.createElement('div'); + holder.style.cssText = + 'position: absolute; left: 20px; top: 120px; width: 335px;'; + holder.innerHTML = `
    ${[ + 1, 2, 3, 4, 5, + ] + .map( + i => + `
  1. Item ${i}
  2. `, + ) + .join('')}
`; + document.body.append(holder); + const list = document.getElementById('numbered')?.getBoundingClientRect(); + const later = document.getElementById('item5')?.getBoundingClientRect(); + return list == null || later == null + ? null + : { + x: list.left, + y: later.top, + width: later.left - list.left, + height: later.height, + }; + }); + if (clip == null) { + throw new Error('no ordered list'); + } + const before = await page.screenshot({clip}); + await page.evaluate(() => window.__lift.lift('item2', 0.2)); + await page.waitForTimeout(600); + const lifted = await page.screenshot({clip}); + const placeholder = await page.evaluate(() => { + const element = document.querySelector('[data-lift-placeholder]'); + return element == null + ? null + : {tag: element.localName, display: getComputedStyle(element).display}; + }); + // The fifth item still reads "5.". + expect(Buffer.compare(lifted, before), JSON.stringify(placeholder)).toBe(0); + expect(placeholder?.tag).toBe('li'); + await page.evaluate(() => window.__lift.dispose()); +}); + test('the shadow follows the row on every frame of its lift and of its drop', async ({ page, }) => { From e0eb8e183c772f5586605de09ee8786d81975c16 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 22:17:57 -0700 Subject: [PATCH 23/65] fix(liftFromTrigger): an li holds a list item's spot, and takes no number In a ul, ol or menu the placeholder is an li, so the list keeps only li children, as a row menu attached to its list item needs. It is laid out as a block, never a list item, so the items after it keep their numbers, and its own minimum and maximum sizes, padding and border are reset, so the page's rules for an li never change the spot it holds. --- .../src/liftFromTrigger/liftFromTrigger.ts | 38 ++++++++++++++++--- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index c9b2853d3ed9c..64b794844053c 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -32,7 +32,8 @@ * kept as it was laid out, and the source takes no hits while lifted (a tap * on it is a tap on the backdrop). Inheritance follows the DOM, so the page's * theme still reaches it. The placeholder goes after the source, so the - * source keeps its place among its siblings. The tint is the `::backdrop` of + * source keeps its place among its siblings; in a list it is an `li` that + * is not a list item, so the list stays valid and keeps its numbers. The tint is the `::backdrop` of * a lift layer at the end of the body that covers the viewport and takes the * page's touches (its color and the gutter's spacing resolved where the * source is); the shadow is a box in the layer that follows the source on a @@ -531,26 +532,51 @@ function createLayer(doc: Document, attribute: string): HTMLElement { return layer; } +/** + * The element that holds a source's spot: an `li` in a list, so the list + * keeps only `li` children (HTML's content model for `ul`, `ol` and `menu`), + * and a `span` elsewhere. + */ +function placeholderTag(source: HTMLElement): 'li' | 'span' { + const parent = source.parentElement?.localName; + return parent === 'ul' || parent === 'ol' || parent === 'menu' + ? 'li' + : 'span'; +} + /** * The placeholder that holds a source's spot in the page while it is lifted: * empty, hidden, at its laid-out size, with its margins and its place in a - * flex or grid container. + * flex or grid container. It is never a list item itself, so it takes no + * number and the items after it keep theirs, and the page's own rules for + * its tag (an `li`'s minimum height, its padding) never change its size. */ function placeholderStyle( computed: CSSStyleDeclaration, box: MorphRect, ): Partial { + const shown = computed.getPropertyValue('display'); const display = - computed.display === 'inline' + shown === 'inline' ? 'inline-block' - : computed.display === 'contents' || computed.display === 'none' + : shown === 'contents' || shown === 'none' ? 'block' - : computed.display; + : shown.includes('list-item') + ? shown.includes('inline') + ? 'inline-block' + : 'block' + : shown; return { display, boxSizing: 'border-box', width: `${box.width}px`, height: `${box.height}px`, + minWidth: '0', + minHeight: '0', + maxWidth: 'none', + maxHeight: 'none', + padding: '0', + border: '0', marginTop: computed.marginTop, marginRight: computed.marginRight, marginBottom: computed.marginBottom, @@ -851,7 +877,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { layer.append(anchor); let placeholder: HTMLElement | null = null; if (placeholderValues != null) { - placeholder = doc.createElement('span'); + placeholder = doc.createElement(placeholderTag(source)); placeholder.setAttribute(`${attribute}-placeholder`, ''); placeholder.setAttribute('aria-hidden', 'true'); Object.assign(placeholder.style, placeholderValues); From 08cb1b7cdb301d980b35ee524537bbd12daeca40 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 27 Oct 2026 12:45:37 -0700 Subject: [PATCH 24/65] test(liftFromTrigger): the zoom's copy of a source, through the lift module (INV15) liftCopy places one copy of the source's picture in the caller's host at the source's box (aspect fill, its corners, inert, hidden from assistive technology), against the host's offset, borders and scroll, while the source hides in place with no placeholder; an image source gives its own picture, another the caller's src; a drop shows the source as it was and leaves nothing, twice is once, and with two copies of one source it shows only when the last drops; nothing changes for a source with no box. Red: liftCopy does not exist. --- .../liftFromTrigger/liftFromTrigger.test.ts | 135 +++++++++++++++++- 1 file changed, 134 insertions(+), 1 deletion(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts index f4c60f4c37389..b23a1f8b39078 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -10,7 +10,9 @@ * unmount puts back exactly what the source had inline and takes the rest * away; nothing of it (an element, a document listener, a timer) outlives * it over repeated lifts; the gutter it reads; the holds it takes; taps on - * its backdrop + * its backdrop. And the zoom's copy (liftCopy): one copy of the source's + * picture in the caller's host at the source's box while the source hides + * in place, and a drop that leaves the page as it was * @position Testing; the motion, the top layer and the counts in real * engines are proven in __tests__/liftFromTrigger.interaction.browser.spec.ts */ @@ -20,6 +22,7 @@ import * as inputHold from '../Layer/inputHold'; import { createLiftFromTrigger, type LiftFromTriggerOptions, + liftCopy, } from './liftFromTrigger'; vi.mock('../Layer/inputHold', async importOriginal => ({ @@ -409,3 +412,133 @@ describe('lift', () => { lift.dispose(); }); }); + +describe('liftCopy', () => { + /** + * A viewer's host over the page, and a grid of thumbnails: one a button + * around a picture, one a bare picture with its own inline visibility, one + * that shows no picture. + */ + function renderGrid() { + document.body.innerHTML = ` +
+
    +
  • +
  • B
  • +
  • C
  • +
`; + const host = document.getElementById('host') as HTMLElement; + place(host, 0, 0, 390, 844); + const thumb = document.getElementById('thumb') as HTMLElement; + thumb.style.borderRadius = '12px'; + place(thumb, 40, 300, 100, 100); + const bare = document.getElementById('bare') as HTMLElement; + place(bare, 150, 300, 100, 100); + const plain = document.getElementById('plain') as HTMLElement; + place(plain, 260, 300, 100, 100); + return {host, thumb, bare, plain}; + } + + it("places one copy of the source's picture in the host at the source's box (aspect fill, its corners, inert, hidden from assistive technology); the source hides in place and nothing else is added", () => { + const {host, thumb} = renderGrid(); + const before = count(); + const copy = liftCopy(thumb, {host}); + expect(copy).not.toBeNull(); + expect(count()).toBe(before + 1); + const element = copy?.element as HTMLImageElement; + expect(element.parentElement).toBe(host); + expect(element.localName).toBe('img'); + expect(element.src).toBe('https://example.test/a-thumb.jpg'); + expect(element.alt).toBe(''); + expect(element.getAttribute('aria-hidden')).toBe('true'); + expect(element.hasAttribute('data-astryx-lift-copy')).toBe(true); + expect([ + element.style.position, + element.style.left, + element.style.top, + element.style.width, + element.style.height, + ]).toEqual(['absolute', '40px', '300px', '100px', '100px']); + expect(element.style.objectFit).toBe('cover'); + expect(element.style.borderRadius).toBe('12px'); + expect(element.style.pointerEvents).toBe('none'); + expect(copy?.box).toEqual({x: 40, y: 300, width: 100, height: 100}); + // The source hides where it is: it keeps its layout, so no placeholder. + expect(thumb.style.visibility).toBe('hidden'); + expect(thumb.parentElement?.children).toHaveLength(1); + copy?.drop(); + }); + + it("lays the copy out against the host's own box: its offset, borders and scroll", () => { + const {host, thumb} = renderGrid(); + place(host, 10, 20, 300, 600); + Object.defineProperty(host, 'clientLeft', {value: 2, configurable: true}); + Object.defineProperty(host, 'clientTop', {value: 3, configurable: true}); + Object.defineProperty(host, 'scrollLeft', {value: 5, configurable: true}); + Object.defineProperty(host, 'scrollTop', {value: 7, configurable: true}); + const copy = liftCopy(thumb, {host}); + expect([copy?.element.style.left, copy?.element.style.top]).toEqual([ + '33px', + '284px', + ]); + copy?.drop(); + }); + + it("takes an image source's own picture, or `src` for a source that shows none", () => { + const {host, bare, plain} = renderGrid(); + const fromImage = liftCopy(bare, {host, src: 'https://example.test/b.jpg'}); + expect(fromImage?.element.src).toBe('https://example.test/b-thumb.jpg'); + fromImage?.drop(); + const fromSrc = liftCopy(plain, {host, src: 'https://example.test/c.jpg'}); + expect(fromSrc?.element.src).toBe('https://example.test/c.jpg'); + fromSrc?.drop(); + }); + + it('a drop takes the copy away and shows the source as it was; a second drop does nothing', () => { + const {host, thumb, bare} = renderGrid(); + const before = count(); + const copy = liftCopy(thumb, {host}); + const other = liftCopy(bare, {host}); + copy?.drop(); + copy?.drop(); + expect(thumb.style.visibility).toBe(''); + expect(thumb.getAttribute('style')).not.toContain('visibility'); + expect(bare.style.visibility).toBe('hidden'); + other?.drop(); + // Its own inline visibility comes back. + expect(bare.style.visibility).toBe('visible'); + expect(count()).toBe(before); + expect(host.children).toHaveLength(0); + }); + + it('two copies of one source: it shows again only when the last of them drops', () => { + const {host, thumb} = renderGrid(); + const opening = liftCopy(thumb, {host}); + const closing = liftCopy(thumb, {host}); + expect(host.children).toHaveLength(2); + opening?.drop(); + expect(thumb.style.visibility).toBe('hidden'); + closing?.drop(); + expect(thumb.style.visibility).toBe(''); + }); + + it('`attribute` names the mark on the copy', () => { + const {host, thumb} = renderGrid(); + const copy = liftCopy(thumb, {host, attribute: 'data-lightbox-portal'}); + expect(copy?.element.hasAttribute('data-lightbox-portal')).toBe(true); + expect(copy?.element.hasAttribute('data-astryx-lift-copy')).toBe(false); + copy?.drop(); + }); + + it('changes nothing for a source that is not in the page or has no box', () => { + const {host, thumb} = renderGrid(); + const before = count(); + const detached = document.createElement('img'); + place(detached, 0, 0, 100, 100); + expect(liftCopy(detached, {host})).toBeNull(); + place(thumb, 40, 300, 0, 0); + expect(liftCopy(thumb, {host})).toBeNull(); + expect(thumb.style.visibility).toBe(''); + expect(count()).toBe(before); + }); +}); From d5fb3789c28ec48e3ba4ab31bc78126cabd765b8 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 27 Oct 2026 12:47:40 -0700 Subject: [PATCH 25/65] feat(liftFromTrigger): liftCopy, the zoom's copy of a source through the lift module (INV15) A zoom from a thumbnail into a viewer needs the thumbnail's picture between the viewer's backdrop and its photo, which a trigger in the top layer cannot be (it would cover the viewer, or sit under its backdrop). liftCopy is INV15's clone: one image of the source's picture (aspect fill, its corners) in the caller's host at the source's box, inert and hidden from assistive technology, while the source hides in place and keeps its layout. The caller moves the copy on the rect morph, which turns an interrupted motion around from the rect on screen; drop() takes the copy away and shows the source as it was once the last copy of it drops. Internal, not exported. --- .changeset/lift-module.md | 2 +- packages/core/src/liftFromTrigger/README.md | 25 ++- .../src/liftFromTrigger/liftFromTrigger.ts | 177 +++++++++++++++++- 3 files changed, 195 insertions(+), 9 deletions(-) diff --git a/.changeset/lift-module.md b/.changeset/lift-module.md index b0d245df28b34..6d6b6ea44e3c2 100644 --- a/.changeset/lift-module.md +++ b/.changeset/lift-module.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, four elements while lifted. Not exported from the package entry point; no component uses it yet. +[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, four elements while lifted. A zoom from a thumbnail lifts a copy of the thumbnail's picture into the viewer instead, while the thumbnail hides in place. Not exported from the package entry point; no component uses it yet. @vjeux diff --git a/packages/core/src/liftFromTrigger/README.md b/packages/core/src/liftFromTrigger/README.md index 92e02b89072cb..ae013e6432886 100644 --- a/packages/core/src/liftFromTrigger/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -1,10 +1,11 @@ # LiftFromTrigger The one lift-from-trigger presentation, internal to core and opt-in. A -surface that chooses it (ContextMenu's touch invocation today) lifts its -trigger out of the page above a tinted backdrop, grows a surface (a menu) out -of the press beside it, shrinks that surface back into the press when it -closes, and returns the trigger to its place. Nothing else gets it by +surface that chooses it (ContextMenu's touch invocation) lifts its trigger +out of the page above a tinted backdrop, grows a surface (a menu) out of the +press beside it, shrinks that surface back into the press when it closes, and +returns the trigger to its place. A viewer's zoom from a thumbnail lifts a +copy of the thumbnail's picture instead (below). Nothing else gets it by default, and any surface that lifts uses this module, never a copy of it. Nothing here is exported from the package entry point; components import it by path. @@ -31,6 +32,22 @@ while it closes: never more than five (`spec:AST-017` FR60, DEC-29). The exit copy the surface shrinks on is the layer runtime's transient copy. At rest there is nothing. +## The zoom's copy + +A zoom from a thumbnail into a viewer (UIKit's `.zoom`) needs the +thumbnail's picture between the viewer's backdrop and its photo, which a +trigger in the top layer cannot be: it would cover the whole viewer, or sit +under its backdrop. So `liftCopy(source, {host, src})` lifts a copy, the one +transient clone `architecture:layer-runtime` INV15 allows: one image of the +source's picture (aspect fill, its corners) in the viewer's host at the +source's box, inert and hidden from assistive technology, while the source +hides where it stands and keeps its layout (no placeholder). The viewer moves +the copy on the rect morph with its own paths and springs; a close during the +opening turns the same copy around from the rect on screen, with its +velocity. `drop()` at the landing, or on unmount, takes the copy away and +shows the source as it was, once the last copy of it drops. While a copy is +up the page has one element more. + ## Motion Every motion is `translate`, `scale` or `opacity` on the compositor diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 64b794844053c..8956352117673 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -11,12 +11,13 @@ * viewport gutter and declared inset * @output Exports createLiftFromTrigger: lift a source out of the page above a tinted * backdrop, grow a surface out of the press beside it, shrink the surface - * back into the press, and return the source to its place + * back into the press, and return the source to its place; and liftCopy: + * a copy of a source's picture in a viewer's host, for a zoom * @position The one lift-from-trigger presentation, internal to core and * opt-in: only a surface that chooses it uses it (ContextMenu's touch - * invocation today). Layer stays generic: the top layer, dismissal, the - * input hold and the shared exit copy are its; this module only - * uses them + * invocation; a viewer's zoom from a thumbnail). Layer stays generic: the + * top layer, dismissal, the input hold and the shared exit copy are its; + * this module only uses them * * UIKit's context menu lifts the long-pressed view out of the page: it grows * on from the size the press gave it to its lifted size, a shadow rising @@ -47,6 +48,16 @@ * its close plays on the layer runtime's one exit copy * (`placeLayerExitCopy`). * + * A zoom from a thumbnail into a viewer lifts a copy instead + * (`architecture:layer-runtime` INV15's clone): the copy has to show between + * the viewer's backdrop and its photo, which a source in the top layer cannot + * (it would cover the whole viewer, or sit under its backdrop). liftCopy puts + * one copy of the source's picture in the viewer's host at the source's box, + * inert and hidden from assistive technology, and hides the source where it + * stands (it keeps its layout, so no placeholder); the viewer moves the copy + * on the rect morph, which turns an interrupted motion around from the rect + * on screen, and a drop shows the source again and takes the copy away. + * * Every motion is `translate`, `scale` or `opacity` on the compositor * (spec:AST-094 FR5): the source and the surface on the rect morph, which * interrupts itself with the velocity on screen (FR6), the shadow on one of @@ -200,6 +211,38 @@ export interface LiftFromTrigger { isLifted(): boolean; } +/** Where a copy goes, and how it is marked. */ +export interface LiftCopyOptions { + /** + * The element the copy goes in (a viewer's container): positioned, so the + * copy is laid out against its box; its stacking decides what the copy + * shows over and under. + */ + readonly host: HTMLElement; + /** The picture for a source that shows none. */ + readonly src?: string; + /** Marks the copy. @default 'data-astryx-lift-copy' */ + readonly attribute?: string; +} + +/** A copy of a source's picture, lifted into a host while the source hides. */ +export interface LiftedCopy { + /** + * The copy: an image in the host, laid out at the source's box (aspect + * fill, its corners), inert and hidden from assistive technology. Move it + * on the rect morph (`createRectMorph(copy.element)`). + */ + readonly element: HTMLImageElement; + /** The source's box, client px, where the copy is laid out. */ + readonly box: MorphRect; + /** + * Takes the copy away and shows the source again, as it was, once the last + * copy of it drops: at the landing, or on unmount (nothing is left either + * way). A second call does nothing. + */ + drop(): void; +} + type SavedStyle = [property: string, value: string, priority: string][]; interface LiftedSurface { @@ -1301,3 +1344,129 @@ export function createLiftFromTrigger(): LiftFromTrigger { isLifted: () => state?.isSourceLifted === true, }; } + +/** + * Sources a copy hides: how many copies hold each, and the visibility it had + * inline before the first, which it gets back when the last drops. + */ +const hiddenSources = new WeakMap< + HTMLElement, + {holders: number; visibility: [value: string, priority: string]} +>(); + +/** Hides `source` where it stands until the returned call lets go. */ +function hideSource(source: HTMLElement): () => void { + const held = hiddenSources.get(source); + if (held == null) { + hiddenSources.set(source, { + holders: 1, + visibility: [ + source.style.getPropertyValue('visibility'), + source.style.getPropertyPriority('visibility'), + ], + }); + source.style.setProperty('visibility', 'hidden', 'important'); + } else { + held.holders += 1; + } + let isReleased = false; + return () => { + const entry = hiddenSources.get(source); + if (isReleased || entry == null) { + return; + } + isReleased = true; + entry.holders -= 1; + if (entry.holders > 0) { + return; + } + hiddenSources.delete(source); + const [value, priority] = entry.visibility; + if (value === '') { + source.style.removeProperty('visibility'); + } else { + source.style.setProperty('visibility', value, priority); + } + }; +} + +/** The picture a source shows: an image's own, or the first one inside it. */ +function pictureOf(source: HTMLElement): string { + const image = + source instanceof HTMLImageElement + ? source + : source.querySelector('img'); + return image?.currentSrc || image?.src || ''; +} + +/** + * Lifts a copy of `source`'s picture into `host` for a zoom + * (`architecture:layer-runtime` INV15's clone): one image laid out at the + * source's box (aspect fill, its corners), inert and hidden from assistive + * technology, while the source hides where it stands. The caller moves the + * copy on the rect morph and drops it at the landing. Null, with nothing + * changed, for a source that is not in the page or has no box. + */ +export function liftCopy( + source: HTMLElement, + {host, src, attribute = 'data-astryx-lift-copy'}: LiftCopyOptions, +): LiftedCopy | null { + if (!source.isConnected || !host.isConnected) { + return null; + } + // Reads before writes: the page lays out once for the copy. + const shown = source.getBoundingClientRect(); + if (shown.width <= 0 || shown.height <= 0) { + return null; + } + const box: MorphRect = { + x: shown.left, + y: shown.top, + width: shown.width, + height: shown.height, + }; + // The host's padding box is the copy's containing block. + const origin = host.getBoundingClientRect(); + const left = box.x - origin.left - host.clientLeft + host.scrollLeft; + const top = box.y - origin.top - host.clientTop + host.scrollTop; + const radius = shapeRadius(source); + const picture = pictureOf(source) || src || ''; + const copy = source.ownerDocument.createElement('img'); + copy.src = picture; + copy.alt = ''; + copy.setAttribute('aria-hidden', 'true'); + copy.setAttribute('inert', ''); + copy.setAttribute(attribute, ''); + Object.assign(copy.style, { + position: 'absolute', + left: `${left}px`, + top: `${top}px`, + width: `${box.width}px`, + height: `${box.height}px`, + // Exactly the box, whatever the host's styles say about images. + margin: '0', + padding: '0', + border: '0', + maxWidth: 'none', + maxHeight: 'none', + boxSizing: 'border-box', + objectFit: 'cover', + borderRadius: radius, + pointerEvents: 'none', + }); + host.append(copy); + const release = hideSource(source); + let isDropped = false; + return { + element: copy, + box, + drop: () => { + if (isDropped) { + return; + } + isDropped = true; + copy.remove(); + release(); + }, + }; +} From 9d4bf2b8ae46b615b3ebf85519caf3893a7a64a0 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 27 Oct 2026 12:54:31 -0700 Subject: [PATCH 26/65] test(liftFromTrigger): browser proofs of the zoom's copy On the fixture, in Chromium and WebKit: the copy lifts into a viewer at the thumbnail's box, one element more and not in the top layer, so the viewer's stacking puts it under the photo, while the thumbnail hides and keeps its layout; it grows toward the photo on the rect morph, a close once it is well on its way turns the same element around from the rect on screen with no frame jumping to either end, and it lands in the thumbnail; the drop shows the thumbnail and leaves the page as it was. --- packages/core/src/liftFromTrigger/README.md | 12 +- .../__tests__/liftFromTrigger.fixture.ts | 22 ++- ...iftFromTrigger.interaction.browser.spec.ts | 156 +++++++++++++++++- 3 files changed, 180 insertions(+), 10 deletions(-) diff --git a/packages/core/src/liftFromTrigger/README.md b/packages/core/src/liftFromTrigger/README.md index ae013e6432886..57d07ef027d01 100644 --- a/packages/core/src/liftFromTrigger/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -62,9 +62,9 @@ document listeners end with it, and an unmount ends everything at once ## Files -| File | What it is | -| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `liftFromTrigger.ts` | `createLiftFromTrigger`: lift a trigger, grow and close a surface beside it, drop, end. | -| `useLiftFromTrigger.ts` | A component's one lift, ended when it unmounts. | -| `liftFromTriggerGeometry.ts` | How far the trigger grows, where it lands inside the layer runtime's gutter, which side the surface takes. | -| `__tests__/liftFromTrigger.interaction.browser.spec.ts` | Browser proofs (Chromium and WebKit): the top layer, the placeholder, the properties that move, counts, leaks. | +| File | What it is | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `liftFromTrigger.ts` | `createLiftFromTrigger`: lift a trigger, grow and close a surface beside it, drop, end. `liftCopy`: the zoom's copy. | +| `useLiftFromTrigger.ts` | A component's one lift, ended when it unmounts. | +| `liftFromTriggerGeometry.ts` | How far the trigger grows, where it lands inside the layer runtime's gutter, which side the surface takes. | +| `__tests__/liftFromTrigger.interaction.browser.spec.ts` | Browser proofs (Chromium and WebKit): the top layer, the placeholder, the properties that move, counts, leaks, the zoom's copy. | diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts index 38bf875ef0681..9528151553a35 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts @@ -7,12 +7,16 @@ * (the first row rounded by `:first-child`, the second holding twelve * elements), a menu popover beside it, and `window.__lift`: lift a row, * grow and close the menu, drop, end, and the backdrop taps and the - * clicks the page received + * clicks the page received; and a thumbnail, a hidden viewer with its + * photo, and `window.__zoom` (liftCopy and the rect morph) for the zoom's + * copy * @position Browser fixture of liftFromTrigger.interaction.browser.spec.ts; test-only */ +import {createRectMorph, lerpPath} from '../../motion/rectMorph'; import { createLiftFromTrigger, + liftCopy, type LiftFromTriggerOptions, type LiftFromTriggerResult, } from '../liftFromTrigger'; @@ -35,9 +39,17 @@ export interface LiftFixture { isLifted: () => boolean; } +/** What a zoom proof drives: the copy, and the rect morph that moves it. */ +export interface ZoomFixture { + liftCopy: typeof liftCopy; + createRectMorph: typeof createRectMorph; + lerpPath: typeof lerpPath; +} + declare global { interface Window { __lift: LiftFixture; + __zoom: ZoomFixture; } } @@ -67,7 +79,11 @@ document.body.innerHTML = ` - `; + + + `; function element(id: string): HTMLElement { const found = document.getElementById(id); @@ -112,6 +128,8 @@ function options(response: number): LiftFromTriggerOptions { }; } +window.__zoom = {liftCopy, createRectMorph, lerpPath}; + window.__lift = { log, lift: (id, springResponse = 0.3) => diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index c307c536d1366..22bae5939672b 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -4,7 +4,8 @@ * @file liftFromTrigger.interaction.browser.spec.ts * @input The lift bundled with esbuild onto a blank fixture page * (liftFromTrigger.fixture.ts): a list of rows in a clipping, transformed panel and a - * menu popover; Chromium and WebKit + * menu popover, a thumbnail and a viewer with its photo; Chromium and + * WebKit * @output Proof in real engines that a row lifts itself into the top layer * at its lifted rect while one placeholder holds its spot (nothing else * moves, and the row keeps its look); that every motion the lift plays is @@ -17,7 +18,11 @@ * the drop * (AST-017 FR60); that repeated lifts leave no node or listener behind; * that a tap while it grows reaches nothing (FR35) and one on the backdrop - * afterwards is the backdrop tap + * afterwards is the backdrop tap; that the zoom's copy lifts into the + * viewer at the thumbnail's box (one element more, stacked by the viewer, + * the thumbnail hidden in place), grows on the rect morph, turns around + * from the rect on screen as the same element and lands in the thumbnail, + * and that its drop leaves the page as it was * @position Browser proof for liftFromTrigger.ts, run by `pnpm test:interaction`; jsdom * has no layout, no top layer and no animations */ @@ -613,3 +618,150 @@ test('a tap while the row and the menu grow reaches nothing; one on the backdrop expect(settled.clicks).not.toContain('page'); await page.evaluate(() => window.__lift.dispose()); }); + +test("a zoom's copy lifts into the viewer at the thumbnail's box, where the viewer's stacking puts it under the photo, while the thumbnail hides in place; one element more", async ({ + page, +}) => { + await open(page); + const read = await page.evaluate(() => { + const box = (element: Element | null): Box => { + const r = element?.getBoundingClientRect(); + return r == null ? [0, 0, 0, 0] : [r.x, r.y, r.width, r.height]; + }; + const viewer = document.getElementById('viewer') as HTMLElement; + const thumb = document.getElementById('thumb') as HTMLElement; + viewer.style.display = 'block'; + const count = () => document.body.querySelectorAll('*').length; + const rest = count(); + const thumbBefore = box(thumb); + const copy = window.__zoom.liftCopy(thumb, {host: viewer}); + if (copy == null) { + throw new Error('no copy'); + } + // Under the photo: the viewer's stacking, as Lightbox sets it. + copy.element.style.zIndex = '-1'; + const result = { + added: count() - rest, + copy: box(copy.element), + thumb: box(thumb), + thumbBefore, + thumbVisibility: getComputedStyle(thumb).visibility, + parentIsViewer: copy.element.parentElement === viewer, + inTopLayer: + copy.element.hasAttribute('popover') || + copy.element.matches(':popover-open'), + radius: getComputedStyle(copy.element).borderTopLeftRadius, + fit: getComputedStyle(copy.element).objectFit, + hidden: copy.element.getAttribute('aria-hidden'), + }; + copy.drop(); + return { + ...result, + afterAdded: count() - rest, + afterVisibility: getComputedStyle(thumb).visibility, + }; + }); + expect(read.added).toBe(1); + expectBox(read.copy, read.thumbBefore); + // The thumbnail keeps its layout: nothing moves in the page. + expectBox(read.thumb, read.thumbBefore); + expect(read.thumbVisibility).toBe('hidden'); + expect(read.parentIsViewer).toBe(true); + expect(read.inTopLayer).toBe(false); + expect(read.radius).toBe('10px'); + expect(read.fit).toBe('cover'); + expect(read.hidden).toBe('true'); + expect(read.afterAdded).toBe(0); + expect(read.afterVisibility).toBe('visible'); +}); + +test('the copy grows to the photo on the rect morph, a close mid-growth turns the same copy around from the rect on screen with no jump, and it lands in the thumbnail; the drop leaves the page as it was', async ({ + page, +}) => { + await open(page); + const run = await page.evaluate(async () => { + const viewer = document.getElementById('viewer') as HTMLElement; + const thumb = document.getElementById('thumb') as HTMLElement; + const photo = document.getElementById('photo') as HTMLElement; + viewer.style.display = 'block'; + const count = () => document.body.querySelectorAll('*').length; + const rest = count(); + const copy = window.__zoom.liftCopy(thumb, {host: viewer}); + if (copy == null) { + throw new Error('no copy'); + } + const element = copy.element; + const r = photo.getBoundingClientRect(); + const fitted = {x: r.x, y: r.y, width: r.width, height: r.height}; + const morph = window.__zoom.createRectMorph(element); + const path = window.__zoom.lerpPath(copy.box, fitted, { + box: copy.box, + scale: 'uniform', + }); + const spring = {response: 0.6, dampingRatio: 1}; + // One sample a frame of where the copy is drawn, and whether it is still + // the same element in the host. + const samples: {t: number; width: number; phase: string}[] = []; + let phase = 'open'; + let sampling = true; + let remounted = false; + // The close comes once the copy is well on its way (150 px wide), however + // fast the engine draws frames. + let midway = () => {}; + const isMidway = new Promise(resolve => { + midway = resolve; + setTimeout(resolve, 2000); + }); + const sample = (t: number) => { + remounted ||= !element.isConnected || element.parentElement !== viewer; + const width = element.getBoundingClientRect().width; + samples.push({t, width, phase}); + if (width >= 150) { + midway(); + } + if (sampling) { + requestAnimationFrame(sample); + } + }; + requestAnimationFrame(sample); + morph.present(path, spring); + await isMidway; + // The close turns the opening around: the same copy, from where it is. + phase = 'close'; + const closing = morph.dismiss(path, spring, {target: element}); + await closing.finished; + sampling = false; + const landed = element.getBoundingClientRect(); + const thumbBox = thumb.getBoundingClientRect(); + morph.dispose(); + copy.drop(); + return { + samples, + remounted, + landed: [landed.x, landed.y, landed.width, landed.height] as Box, + thumb: [thumbBox.x, thumbBox.y, thumbBox.width, thumbBox.height] as Box, + afterAdded: count() - rest, + afterVisibility: getComputedStyle(thumb).visibility, + photoWidth: fitted.width, + }; + }); + expect(run.remounted).toBe(false); + const opening = run.samples.filter(s => s.phase === 'open'); + const closing = run.samples.filter(s => s.phase === 'close'); + expect(opening.length).toBeGreaterThan(1); + expect(closing.length).toBeGreaterThan(1); + // It was growing toward the photo when the close came. + const lastOpen = opening[opening.length - 1].width; + expect(lastOpen).toBeGreaterThanOrEqual(150); + expect(lastOpen).toBeLessThan(run.photoWidth); + // The close starts where the opening was drawn: its first frame is nearer + // that than either end, so no frame jumps back to the thumbnail or on to + // the photo. + expect(Math.abs(closing[0].width - lastOpen)).toBeLessThan( + Math.min(lastOpen - 80, run.photoWidth - lastOpen), + ); + // It lands exactly in the thumbnail. + expectBox(run.landed, run.thumb, 1); + expect(run.afterAdded).toBe(0); + expect(run.afterVisibility).toBe('visible'); +}); From 5ef5f3699cbeb14b78801967f89071d315c9692d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 27 Oct 2026 00:42:49 -0700 Subject: [PATCH 27/65] docs(layer-runtime): the lift-from-trigger module exists The gaps paragraph said no lift module exists. With the module in packages/core/src/liftFromTrigger/, it names it under INV15 and keeps the gap that remains: no runtime backdrop tint. --- docs/architecture/layer-runtime.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 6b215ab97950d..ef6b0f94ae461 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -663,7 +663,8 @@ be updated only as that work ships. INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them. The runtime owns the shared exit copy (INV13, `placeLayerExitCopy`) and the shared presentation hold (`Layer/presentationHold.ts`), which Popover uses for its -sheet and anchored presentations; no runtime backdrop tint or lift module +sheet and anchored presentations, and the one lift-from-trigger module exists +(INV15, `packages/core/src/liftFromTrigger/`); no runtime backdrop tint exists, and Dialog, Drawer, BottomSheet, Lightbox, MobileNav, ToastViewport, and Selector each build their own top-layer mounting, exit, backdrop, or presentation hold. From 1d704a2b16a1e768c026a241aefa5ce0a32a0d0d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 19:17:35 -0800 Subject: [PATCH 28/65] fix(liftFromTrigger): each spring reaches the rect morph as a motion The rect morph takes a motion, `{spring}` or a duration with a curve, where it took a bare spring. The lift wraps each of its four springs, and the zoom proof its one. --- .../liftFromTrigger.interaction.browser.spec.ts | 4 ++-- .../core/src/liftFromTrigger/liftFromTrigger.ts | 14 ++++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 22bae5939672b..066ac5cf6a1c5 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -724,11 +724,11 @@ test('the copy grows to the photo on the rect morph, a close mid-growth turns th } }; requestAnimationFrame(sample); - morph.present(path, spring); + morph.present(path, {spring}); await isMidway; // The close turns the opening around: the same copy, from where it is. phase = 'close'; - const closing = morph.dismiss(path, spring, {target: element}); + const closing = morph.dismiss(path, {spring}, {target: element}); await closing.finished; sampling = false; const landed = element.getBoundingClientRect(); diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 8956352117673..00781e12eb244 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -979,7 +979,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { holdClock(performance.now()); const growing = morph.present( lerpPath(from, lifted, {box: sourceRect, scale: 'uniform'}), - motion.lift, + {spring: motion.lift}, {crossfadeAs: 'entrance'}, ); holdClock(null); @@ -1162,9 +1162,11 @@ export function createLiftFromTrigger(): LiftFromTrigger { }), ); const morph = createRectMorph(element); - const presenting = morph.present(path, current.motion.surfaceIn, { - crossfadeAs: 'entrance', - }); + const presenting = morph.present( + path, + {spring: current.motion.surfaceIn}, + {crossfadeAs: 'entrance'}, + ); void presenting.finished.then(surfaceSettled, surfaceSettled); current.surface = { element, @@ -1237,7 +1239,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { } surface.dismissing = surface.morph.dismiss( surface.path, - current.motion.surfaceOut, + {spring: current.motion.surfaceOut}, {target: copy, crossfadeAs: 'exit'}, ); }; @@ -1293,7 +1295,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { ); const returning = current.morph.dismiss( lerpPath(sourceRect, lifted, {box: sourceRect, scale: 'uniform'}), - motion.drop, + {spring: motion.drop}, {target: source, crossfadeAs: 'exit'}, ); current.holdClock(null); From 23bf224984c7c56fa1046683841803c0cabacc22 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 19:17:35 -0800 Subject: [PATCH 29/65] refactor(liftFromTrigger): the caller names the lift's marks A private data attribute is written only in its owner module, so the lift writes no name of its own. A lift takes the attribute its caller owns for the layer and its parts, and a zoom's copy is marked only when its caller passes one. --- .../liftFromTrigger/liftFromTrigger.test.ts | 2 -- .../src/liftFromTrigger/liftFromTrigger.ts | 18 ++++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts index b23a1f8b39078..0837ee9fe59d0 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -451,7 +451,6 @@ describe('liftCopy', () => { expect(element.src).toBe('https://example.test/a-thumb.jpg'); expect(element.alt).toBe(''); expect(element.getAttribute('aria-hidden')).toBe('true'); - expect(element.hasAttribute('data-astryx-lift-copy')).toBe(true); expect([ element.style.position, element.style.left, @@ -526,7 +525,6 @@ describe('liftCopy', () => { const {host, thumb} = renderGrid(); const copy = liftCopy(thumb, {host, attribute: 'data-lightbox-portal'}); expect(copy?.element.hasAttribute('data-lightbox-portal')).toBe(true); - expect(copy?.element.hasAttribute('data-astryx-lift-copy')).toBe(false); copy?.drop(); }); diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 00781e12eb244..2c6d15bb726e9 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -156,11 +156,11 @@ export interface LiftFromTriggerOptions { /** A finger lifted on the backdrop where it went down. */ readonly onBackdropTap?: () => void; /** - * Marks the lift's elements: the layer, its placeholder - * (`-placeholder`) and a surface's exit copy - * (`-exit`). + * Marks the lift's elements, a private attribute the caller owns: the + * layer, its placeholder (`-placeholder`) and a surface's exit + * copy (`-exit`). */ - readonly attribute?: string; + readonly attribute: string; } /** Where a lift landed. */ @@ -221,7 +221,7 @@ export interface LiftCopyOptions { readonly host: HTMLElement; /** The picture for a source that shows none. */ readonly src?: string; - /** Marks the copy. @default 'data-astryx-lift-copy' */ + /** Marks the copy, when given: a private attribute the caller owns. */ readonly attribute?: string; } @@ -816,7 +816,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { if (typeof source.showPopover !== 'function' || !source.isConnected) { return null; } - const attribute = options.attribute ?? 'data-astryx-lift'; + const {attribute} = options; const doc = source.ownerDocument; const view = doc.defaultView; const computed = view?.getComputedStyle(source); @@ -1411,7 +1411,7 @@ function pictureOf(source: HTMLElement): string { */ export function liftCopy( source: HTMLElement, - {host, src, attribute = 'data-astryx-lift-copy'}: LiftCopyOptions, + {host, src, attribute}: LiftCopyOptions, ): LiftedCopy | null { if (!source.isConnected || !host.isConnected) { return null; @@ -1438,7 +1438,9 @@ export function liftCopy( copy.alt = ''; copy.setAttribute('aria-hidden', 'true'); copy.setAttribute('inert', ''); - copy.setAttribute(attribute, ''); + if (attribute != null) { + copy.setAttribute(attribute, ''); + } Object.assign(copy.style, { position: 'absolute', left: `${left}px`, From fe3b5c27b229f3eab1c95d70019beb1de1c06499 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 19:17:35 -0800 Subject: [PATCH 30/65] docs(liftFromTrigger): comments say why, not which record The header keeps to its inputs, outputs and place, and the README holds what a lift adds; it gains the placeholder's list rule and the lifted source taking no hits. Inline comments drop their record citations and keep the reason. --- packages/core/src/liftFromTrigger/README.md | 5 +- .../src/liftFromTrigger/liftFromTrigger.ts | 91 ++++--------------- .../liftFromTriggerGeometry.ts | 21 ++--- .../src/liftFromTrigger/useLiftFromTrigger.ts | 3 +- 4 files changed, 29 insertions(+), 91 deletions(-) diff --git a/packages/core/src/liftFromTrigger/README.md b/packages/core/src/liftFromTrigger/README.md index 57d07ef027d01..1099323b95e87 100644 --- a/packages/core/src/liftFromTrigger/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -21,7 +21,10 @@ rule and gap are the caller's own. The trigger itself lifts, not a copy: it becomes a manual popover in the top layer, laid out at its own size where it stood, so no clipping, transformed or stacking ancestor cuts or covers it, and an empty placeholder after it -holds its spot, so the page does not move. While lifted the page has four +holds its spot, so the page does not move. In a list the placeholder is an +`li` that is not a list item, so the list stays valid and keeps its numbers. +The trigger takes no hits while lifted: a tap on it is a tap on the backdrop. +While lifted the page has four elements more, whatever the trigger holds: the lift layer (its `::backdrop` is the tint); the shadow, a box in the layer that follows the trigger on a rect morph of its own (an animated `::backdrop` of the trigger would restyle diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 2c6d15bb726e9..54fa627f5547a 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -4,70 +4,14 @@ /** * @file liftFromTrigger.ts - * @input An element to lift (the source) and, beside it, a surface that - * grows out of the press (a menu's popover); the caller's springs, scale - * rule and tint; the rect morph - * (motion/rectMorph.ts); the layer runtime's input hold, exit copy, - * viewport gutter and declared inset - * @output Exports createLiftFromTrigger: lift a source out of the page above a tinted - * backdrop, grow a surface out of the press beside it, shrink the surface - * back into the press, and return the source to its place; and liftCopy: - * a copy of a source's picture in a viewer's host, for a zoom + * @input An element to lift (the source), a surface that grows out of the + * press beside it, the caller's springs, scale rule, tint and attribute, + * the rect morph, and the layer runtime's input hold, exit copy and inset + * @output createLiftFromTrigger, which lifts a source above a tinted + * backdrop, grows and shrinks a surface at the press, and puts the source + * back; and liftCopy, a copy of a source's picture for a zoom * @position The one lift-from-trigger presentation, internal to core and - * opt-in: only a surface that chooses it uses it (ContextMenu's touch - * invocation; a viewer's zoom from a thumbnail). Layer stays generic: the - * top layer, dismissal, the input hold and the shared exit copy are its; - * this module only uses them - * - * UIKit's context menu lifts the long-pressed view out of the page: it grows - * on from the size the press gave it to its lifted size, a shadow rising - * under it, above a backdrop that tints the page; the menu grows out of the - * finger beside it, and when the menu closes it shrinks back into the finger - * while the view returns to its place and the backdrop clears. - * - * Here the source itself lifts, not a copy: it becomes a manual popover in - * the top layer, laid out at its own size where it stood, so no clipping, - * transformed or stacking ancestor cuts or covers it, while one empty - * placeholder holds its spot in the page, which does not move. What the - * browser's popover style would change (border, padding, colors, overflow) is - * kept as it was laid out, and the source takes no hits while lifted (a tap - * on it is a tap on the backdrop). Inheritance follows the DOM, so the page's - * theme still reaches it. The placeholder goes after the source, so the - * source keeps its place among its siblings; in a list it is an `li` that - * is not a list item, so the list stays valid and keeps its numbers. The tint is the `::backdrop` of - * a lift layer at the end of the body that covers the viewport and takes the - * page's touches (its color and the gutter's spacing resolved where the - * source is); the shadow is a box in the layer that follows the source on a - * rect morph of its own (an animated `::backdrop` of the source would - * restyle and lay out the page on every frame). The layer also holds an empty box - * at the lifted rect for a surface to be placed against: anchor positioning - * follows transforms, so a box inside the source would move with it. Nothing - * of the lift is in the DOM at rest; while lifted it adds four elements, the - * layer, the shadow, the box and the placeholder - * (`architecture:component-style-authoring` INV7, `spec:AST-017` FR60), and - * its close plays on the layer runtime's one exit copy - * (`placeLayerExitCopy`). - * - * A zoom from a thumbnail into a viewer lifts a copy instead - * (`architecture:layer-runtime` INV15's clone): the copy has to show between - * the viewer's backdrop and its photo, which a source in the top layer cannot - * (it would cover the whole viewer, or sit under its backdrop). liftCopy puts - * one copy of the source's picture in the viewer's host at the source's box, - * inert and hidden from assistive technology, and hides the source where it - * stands (it keeps its layout, so no placeholder); the viewer moves the copy - * on the rect morph, which turns an interrupted motion around from the rect - * on screen, and a drop shows the source again and takes the copy away. - * - * Every motion is `translate`, `scale` or `opacity` on the compositor - * (spec:AST-094 FR5): the source and the surface on the rect morph, which - * interrupts itself with the velocity on screen (FR6), the shadow on one of - * its own along the same path; the tint as a spring-sampled Web Animation of - * the layer's `::backdrop`. A tap or - * a drag that lands while the lift and the surface grow reaches nothing - * (the input hold, FR35); the close holds the layer until the source - * is back, the surface's exit is done and every press on the layer has - * lifted. Its timers and document listeners end with it (FR24). Reduce - * Motion is the animator's (design:reduced-motion): opacity only. + * opt-in. README.md says what a lift adds to the page and how it moves * * SYNC: When modified, update: * - /packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -192,7 +136,8 @@ export interface LiftFromTrigger { * Grows `surface` (a popover laid out at rest, or an element inside one) * out of `press` (client px) into its box, or, without a press, fades it * in where it rests; and holds the lift until the lift and the surface - * settle (spec:AST-094 FR35). A no-op when nothing is lifted. + * settle, so a tap during the growth reaches nothing. A no-op when nothing + * is lifted. */ presentSurface( surface: HTMLElement, @@ -282,7 +227,7 @@ interface LiftState { * shadow reads the motion at the very moment the morph does. */ readonly holdClock: (at: number | null) => void; - /** The layer's own waits and listeners, released with it (FR24). */ + /** The layer's own waits and listeners, released with it. */ readonly waits: AbortController; untilPointersLift: () => Promise; tint: Animation | null; @@ -851,8 +796,8 @@ export function createLiftFromTrigger(): LiftFromTrigger { const radius = shapeRadius(source); const motion = resolvedMotion(source, options.motion); const reduced = reducedMotionFade(source); - // The tint, the shadow and the layer runtime's gutter (spec:AST-059, - // with the inset an app declares), resolved where the source is. + // The tint, the shadow and the layer runtime's gutter, with the inset an + // app declares, resolved where the source is. const probed = probe(source, { ...Object.fromEntries( Object.entries(layerInsetProperties(options.inset)).map( @@ -1082,8 +1027,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { ); current.untilPointersLift = watchPointers(current); // No touch reaches the layer, or anything under it, while the source - // grows (spec:AST-094 FR35); a surface extends the hold to its own - // growth. + // grows; a surface extends the hold to its own growth. current.releaseGrowHold = holdInput(layer, { scope: 'viewport', until: growing.finished, @@ -1091,8 +1035,8 @@ export function createLiftFromTrigger(): LiftFromTrigger { return {source: sourceRect, lifted, viewport, anchor}; }; - // The lift layer takes no touch until the lift and the surface settle - // (spec:AST-094 FR35). The hold's shield joins the top layer after the + // The lift layer takes no touch until the lift and the surface settle. + // The hold's shield joins the top layer after the // surface, so it covers it too; keys and assistive technology stay live. const holdWhileGrowing = ( current: LiftState, @@ -1402,9 +1346,8 @@ function pictureOf(source: HTMLElement): string { } /** - * Lifts a copy of `source`'s picture into `host` for a zoom - * (`architecture:layer-runtime` INV15's clone): one image laid out at the - * source's box (aspect fill, its corners), inert and hidden from assistive + * Lifts a copy of `source`'s picture into `host` for a zoom, the lift's one + * transient copy: one image laid out at the source's box (aspect fill, its corners), inert and hidden from assistive * technology, while the source hides where it stands. The caller moves the * copy on the rect morph and drops it at the landing. Null, with nothing * changed, for a source that is not in the page or has no box. diff --git a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts index a2c603b7c18c8..5bf3f7129f0e4 100644 --- a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts @@ -4,19 +4,12 @@ * @file liftFromTriggerGeometry.ts * @input A source's box, the viewport and the layer runtime's gutter, and * the caller's scale rule and gap - * @output Exports liftFromTriggerScale, liftFromTriggerRect and surfacePlacement: how far a - * lifted source grows, where it lands inside the gutter, and which side of - * it a surface (a menu) takes - * @position The geometry of the lift presentation (liftFromTrigger.ts); internal to - * core - * - * A lifted source grows about its center by the caller's rule (UIKit's - * preview platter: up to a factor, by a number of points on its larger - * side, and never wider than the screen less the gutter), then moves inside - * the layer runtime's viewport gutter (spec:AST-059) if it crosses it. A - * surface sits a gap away: below the source when it fits above the bottom - * gutter, else above; centered on the source, or flush with the edge the - * source is held against. + * @output liftFromTriggerScale, liftFromTriggerRect and surfacePlacement: + * how far a lifted source grows, where it lands inside the gutter, and + * which side of it a surface (a menu) takes + * @position The geometry of the lift presentation (liftFromTrigger.ts); + * internal to core. A source grows about its center by the caller's rule, + * as UIKit's preview platter does, then moves inside the gutter * * SYNC: When modified, update /packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts */ @@ -25,7 +18,7 @@ import type {MorphRect} from '../motion/rectMorph'; /** * The layer runtime's viewport gutter on each edge, CSS px - * (Layer/layerViewportInset.stylex.ts, spec:AST-059): the spacing step or the + * (Layer/layerViewportInset.stylex.ts): the spacing step or the * edge's safe-area inset, whichever is larger, plus the inset an app declares * for a bar floating over that edge. */ diff --git a/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts b/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts index f69d3a40a2b0f..ad3b1a4ba315f 100644 --- a/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/useLiftFromTrigger.ts @@ -18,8 +18,7 @@ import {createLiftFromTrigger, type LiftFromTrigger} from './liftFromTrigger'; /** * The component's lift. It stays the same object for the component's life; - * an unmount ends whatever it has up and leaves the page as it was - * (spec:AST-094 FR24). + * an unmount ends whatever it has up and leaves the page as it was. */ export function useLiftFromTrigger(): LiftFromTrigger { const liftRef = useRef(null); From 6a58c1101e2117cdf3a4ddc0f569e268837bfc92 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 19:57:02 -0800 Subject: [PATCH 31/65] test(liftFromTrigger): a finger taps the growing lift, from the harness The layer runtime's input hold judges each event by its own pointer, so a mouse keeps its clicks during a presentation. The lift is a touch presentation, so its hold proof taps with a finger, before and after the growth settles. The proofs import Playwright through the interaction harness, as the lint rule asks. --- .../__tests__/liftFromTrigger.interaction.browser.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 066ac5cf6a1c5..b87ce5868a17a 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -29,7 +29,7 @@ import path from 'node:path'; import {fileURLToPath} from 'node:url'; -import {expect, test, type Page} from '@playwright/test'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; import {build, type Plugin} from 'esbuild'; // The page's `window.__lift`. import type {LiftFixture} from './liftFromTrigger.fixture'; @@ -607,12 +607,12 @@ test('a tap while the row and the menu grow reaches nothing; one on the backdrop window.__lift.lift('row2', 0.8); window.__lift.presentMenu({x: 180, y: 330}); }); - await page.mouse.click(180, 700); + await page.touchscreen.tap(180, 700); const growing = await page.evaluate(() => ({...window.__lift.log})); expect(growing.backdropTaps).toBe(0); expect(growing.clicks).not.toContain('page'); await page.waitForTimeout(2000); - await page.mouse.click(180, 700); + await page.touchscreen.tap(180, 700); const settled = await page.evaluate(() => ({...window.__lift.log})); expect(settled.backdropTaps).toBe(1); expect(settled.clicks).not.toContain('page'); From 8e4f4c5121d24ef7511cb3b8084632654c1d90d6 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 20:16:13 -0800 Subject: [PATCH 32/65] docs(liftFromTrigger): comment sentences keep to 25 words Each comment sentence in the module, its tests and its fixture keeps to 25 words, one topic each. A long sentence is split, or cut where the README says it already. The header keeps to 12 lines. No code changes. --- .../__tests__/liftFromTrigger.fixture.ts | 12 +- ...iftFromTrigger.interaction.browser.spec.ts | 47 ++--- .../liftFromTrigger/liftFromTrigger.test.ts | 19 +- .../src/liftFromTrigger/liftFromTrigger.ts | 166 +++++++++--------- .../liftFromTriggerGeometry.test.ts | 6 +- .../liftFromTriggerGeometry.ts | 23 ++- 6 files changed, 126 insertions(+), 147 deletions(-) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts index 9528151553a35..8a30b6ec656fc 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts @@ -3,13 +3,11 @@ /** * @file liftFromTrigger.fixture.ts * @input Nothing: bundled by esbuild and injected into a blank page - * @output A page with a list of rows inside a clipping, transformed panel - * (the first row rounded by `:first-child`, the second holding twelve - * elements), a menu popover beside it, and `window.__lift`: lift a row, - * grow and close the menu, drop, end, and the backdrop taps and the - * clicks the page received; and a thumbnail, a hidden viewer with its - * photo, and `window.__zoom` (liftCopy and the rect morph) for the zoom's - * copy + * @output A page with a list of rows in a clipping, transformed panel, and a + * menu popover beside it. The first row is rounded by `:first-child`, and + * the second holds twelve elements. `window.__lift` lifts a row, grows and + * closes the menu, drops and ends, and logs taps and clicks. A thumbnail + * and a hidden viewer serve the zoom's copy through `window.__zoom` * @position Browser fixture of liftFromTrigger.interaction.browser.spec.ts; test-only */ diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index b87ce5868a17a..ef993b7400ed1 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -3,26 +3,14 @@ /** * @file liftFromTrigger.interaction.browser.spec.ts * @input The lift bundled with esbuild onto a blank fixture page - * (liftFromTrigger.fixture.ts): a list of rows in a clipping, transformed panel and a - * menu popover, a thumbnail and a viewer with its photo; Chromium and - * WebKit - * @output Proof in real engines that a row lifts itself into the top layer - * at its lifted rect while one placeholder holds its spot (nothing else - * moves, and the row keeps its look); that every motion the lift plays is - * `translate`, `scale`, `transform` or `opacity` (spec:AST-094 FR5); that - * the menu grows out of the press and keeps nothing inline at rest, and - * its close shrinks the layer runtime's exit copy back into it, or, with - * no press, fades in where it rests; that the - * page has the layer, the shadow, the anchor and the placeholder more while - * lifted, whatever the row holds, at most 5 at any moment, and none after - * the drop - * (AST-017 FR60); that repeated lifts leave no node or listener behind; - * that a tap while it grows reaches nothing (FR35) and one on the backdrop - * afterwards is the backdrop tap; that the zoom's copy lifts into the - * viewer at the thumbnail's box (one element more, stacked by the viewer, - * the thumbnail hidden in place), grows on the rect morph, turns around - * from the rect on screen as the same element and lands in the thumbnail, - * and that its drop leaves the page as it was + * (liftFromTrigger.fixture.ts), in Chromium and WebKit + * @output Proof in real engines of the lift and the zoom's copy. A row lifts + * into the top layer while a placeholder holds its spot. Every motion is + * `translate`, `scale`, `transform` or `opacity`. The menu grows out of the + * press and shrinks back into it on close. The page has at most five more + * elements while lifted, and none after the drop. A tap while it grows + * reaches nothing. The zoom's copy grows on the rect morph, turns around + * and lands in the thumbnail * @position Browser proof for liftFromTrigger.ts, run by `pnpm test:interaction`; jsdom * has no layout, no top layer and no animations */ @@ -197,8 +185,8 @@ test('a lifted item of an ordered list leaves the numbers of the items after it page, }) => { await open(page); - // An ordered list with its markers outside, and no tint and no shadow: a - // later item's marker paints the same while an item is lifted unless its + // An ordered list with its markers outside, and no tint and no shadow. A + // later item's marker paints the same while an item is lifted, unless its // number changes. const clip = await page.evaluate(() => { const root = document.documentElement.style; @@ -503,8 +491,8 @@ test('while lifted the page has the layer, the shadow, the anchor and the placeh }) => { await open(page); const counts = await page.evaluate(async () => { - // The layer runtime's exit copy is the transient copy INV7 allows (made - // by the layer runtime, gone within a second): not one of the lift's. + // The layer runtime's exit copy is not one of the lift's elements: the + // runtime makes it, and it is gone within a second. const count = () => [...document.body.querySelectorAll('*')].filter( element => element.closest('[data-lift-exit]') == null, @@ -552,9 +540,9 @@ test('while lifted the page has the layer, the shadow, the anchor and the placeh lifted: window.__lift.isLifted(), }; }); - // A row of 13 elements and a row of 1: the same 4 more once grown (the - // layer, the shadow, the anchor and the placeholder), and the hold's - // shield while the lift grows. + // A row of 13 elements and a row of 1 add the same 4 once grown: the layer, + // the shadow, the anchor and the placeholder. The hold's shield joins while + // the lift grows. expect(counts.deep).toBe(5); expect(counts.shallow).toBe(5); expect(counts.open).toBe(4); @@ -754,9 +742,8 @@ test('the copy grows to the photo on the rect morph, a close mid-growth turns th const lastOpen = opening[opening.length - 1].width; expect(lastOpen).toBeGreaterThanOrEqual(150); expect(lastOpen).toBeLessThan(run.photoWidth); - // The close starts where the opening was drawn: its first frame is nearer - // that than either end, so no frame jumps back to the thumbnail or on to - // the photo. + // The close starts where the opening was drawn. Its first frame is nearer + // that than either end, so no frame jumps to the thumbnail or the photo. expect(Math.abs(closing[0].width - lastOpen)).toBeLessThan( Math.min(lastOpen - 80, run.photoWidth - lastOpen), ); diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts index 0837ee9fe59d0..d0db0379ea10b 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -4,15 +4,10 @@ * @file liftFromTrigger.test.ts * @input vitest (jsdom), the lift, stand-ins for the popover API and for * layout (jsdom has neither) and a spy on the input hold - * @output Checks the lift's bookkeeping in the page: while up it adds the - * layer and one placeholder whatever the source holds, and nothing at - * rest; the source keeps its place among its siblings; a drop or an - * unmount puts back exactly what the source had inline and takes the rest - * away; nothing of it (an element, a document listener, a timer) outlives - * it over repeated lifts; the gutter it reads; the holds it takes; taps on - * its backdrop. And the zoom's copy (liftCopy): one copy of the source's - * picture in the caller's host at the source's box while the source hides - * in place, and a drop that leaves the page as it was + * @output Checks the lift's bookkeeping in the page. While up it adds the + * layer and one placeholder, and nothing at rest. A drop or an unmount puts + * back what the source had inline. Nothing outlives repeated lifts. It also + * checks the gutter, the holds, backdrop taps and the zoom's copy * @position Testing; the motion, the top layer and the counts in real * engines are proven in __tests__/liftFromTrigger.interaction.browser.spec.ts */ @@ -415,9 +410,9 @@ describe('lift', () => { describe('liftCopy', () => { /** - * A viewer's host over the page, and a grid of thumbnails: one a button - * around a picture, one a bare picture with its own inline visibility, one - * that shows no picture. + * A viewer's host over the page, and a grid of three thumbnails. One is a + * button around a picture, one a bare picture with its own inline + * visibility, and one shows no picture. */ function renderGrid() { document.body.innerHTML = ` diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 54fa627f5547a..a9d5787eec270 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -4,18 +4,15 @@ /** * @file liftFromTrigger.ts - * @input An element to lift (the source), a surface that grows out of the - * press beside it, the caller's springs, scale rule, tint and attribute, - * the rect morph, and the layer runtime's input hold, exit copy and inset - * @output createLiftFromTrigger, which lifts a source above a tinted - * backdrop, grows and shrinks a surface at the press, and puts the source - * back; and liftCopy, a copy of a source's picture for a zoom - * @position The one lift-from-trigger presentation, internal to core and - * opt-in. README.md says what a lift adds to the page and how it moves + * @input A source to lift, a surface to grow beside it, and the caller's + * springs, scale rule, tint and attribute + * @output createLiftFromTrigger, which lifts a source and grows a surface at + * the press; and liftCopy, a copy of a source's picture for a zoom + * @position The one lift-from-trigger presentation, internal and opt-in. + * README.md says what a lift adds to the page and how it moves * - * SYNC: When modified, update: - * - /packages/core/src/liftFromTrigger/liftFromTrigger.test.ts - * - /packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts + * SYNC: When modified, update liftFromTrigger.test.ts and + * __tests__/liftFromTrigger.interaction.browser.spec.ts. */ import type {LayerInset} from '../Layer/LayerContext'; @@ -47,9 +44,8 @@ import { } from './liftFromTriggerGeometry'; /** - * How long the layer waits, once the last pointer that went down on it has - * lifted, for that touch's click before it hides anyway (a long press sends - * none). + * How long the layer waits for a touch's click after the last pointer on it + * lifts. A long press sends no click, so the layer then hides anyway. */ const CLICK_AFTER_LIFT_MS = 350; @@ -86,9 +82,9 @@ export interface LiftFromTriggerOptions { */ readonly from?: MorphRect; /** - * Called once the lift has read the page and before it writes to it: lets - * go of what the source was doing (a press feedback's scale), so letting go - * doesn't restyle the page before the lift reads it. + * Called after the lift reads the page and before it writes to it. It lets + * go of what the source was doing, such as a press feedback's scale. The + * release then cannot restyle the page before the lift reads it. */ readonly release?: () => void; /** The tint, a CSS color resolved where the source is. */ @@ -116,9 +112,9 @@ export interface LiftFromTriggerResult { /** The viewport and the layer runtime's gutter it lifted in. */ readonly viewport: LiftFromTriggerViewport; /** - * An empty box at the lifted rect, in the layer: what a surface is placed - * against (an anchor inside the source would move with the source's - * transform, which anchor positioning follows). + * An empty box at the lifted rect, in the layer, for a surface to be + * placed against. Anchor positioning follows transforms, so an anchor + * inside the source would move with it. */ readonly anchor: HTMLElement; } @@ -133,11 +129,11 @@ export interface LiftFromTrigger { options: LiftFromTriggerOptions, ): LiftFromTriggerResult | null; /** - * Grows `surface` (a popover laid out at rest, or an element inside one) - * out of `press` (client px) into its box, or, without a press, fades it - * in where it rests; and holds the lift until the lift and the surface - * settle, so a tap during the growth reaches nothing. A no-op when nothing - * is lifted. + * Grows `surface` out of `press` (client px) into its box: a popover laid + * out at rest, or an element inside one. Without a press, it fades the + * surface in where it rests. The lift holds input until the lift and the + * surface settle, so a tap during the growth reaches nothing. A no-op when + * nothing is lifted. */ presentSurface( surface: HTMLElement, @@ -159,9 +155,9 @@ export interface LiftFromTrigger { /** Where a copy goes, and how it is marked. */ export interface LiftCopyOptions { /** - * The element the copy goes in (a viewer's container): positioned, so the - * copy is laid out against its box; its stacking decides what the copy - * shows over and under. + * The element the copy goes in, such as a viewer's container. It is + * positioned, so the copy is laid out against its box. Its stacking decides + * what the copy shows over and under. */ readonly host: HTMLElement; /** The picture for a source that shows none. */ @@ -181,9 +177,9 @@ export interface LiftedCopy { /** The source's box, client px, where the copy is laid out. */ readonly box: MorphRect; /** - * Takes the copy away and shows the source again, as it was, once the last - * copy of it drops: at the landing, or on unmount (nothing is left either - * way). A second call does nothing. + * Takes the copy away. Once the last copy of the source drops, the source + * shows again as it was. Call it at the landing or on unmount; nothing is + * left either way. A second call does nothing. */ drop(): void; } @@ -217,8 +213,8 @@ interface LiftState { /** The tint's color, held on the layer's `::backdrop`. */ readonly layerFill: Animation | null; /** - * The shadow under the source: a box in the layer laid out where the - * source is, which follows it frame for frame and fades on its own spring. + * The shadow under the source, a box in the layer laid out where the source + * is. It follows the source frame for frame and fades on its own spring. */ readonly shadow: HTMLElement; shadowAnimation: Animation | null; @@ -293,11 +289,12 @@ function springKeyframes( } /** - * Web Animation keyframes for a box laid out on `box` that travels from - * `from` to `to` on `travel` (starting with progress velocity `velocity`, as - * the rect morph does) while its opacity goes from `fade[0]` to `fade[1]` on - * `fadeSpring`, sampled at 60 Hz until both settle: one compositor animation - * of `transform` and `opacity`, frame for frame with the source's own morph. + * Web Animation keyframes for a box laid out on `box`. It travels from + * `from` to `to` on `travel`, starting at progress velocity `velocity`, as the + * rect morph does. Its opacity goes from `fade[0]` to `fade[1]` on + * `fadeSpring`. The keyframes sample both at 60 Hz until both settle. The + * result is one compositor animation of `transform` and `opacity`, frame for + * frame with the source's morph. */ function shadowKeyframes( box: MorphRect, @@ -379,10 +376,10 @@ function shapeRadius(source: HTMLElement): string { } /** - * Resolves CSS values where `element` is (its theme, its color scheme): on an - * empty, undisplayed child it removes again, so the element's own style and - * the page's layout stay as they were. A pair is a fallback and a value a - * browser may reject. + * Resolves CSS values where `element` is, in its theme and color scheme. It + * reads them on an empty, undisplayed child and removes the child again. So + * the element's own style and the page's layout stay as they were. A pair is + * a fallback and a value a browser may reject. */ function probe( element: HTMLElement, @@ -410,9 +407,9 @@ function probe( } /** - * The lift's springs as they resolve at `element` (a spring that is a motion - * role, through its role), read once: plain springs, which nothing reads - * from the page again. + * The lift's springs as they resolve at `element`, read once. A spring that + * is a motion role resolves through its role. The result is plain springs, + * and nothing reads the page for them again. */ function resolvedMotion( element: Element, @@ -521,9 +518,8 @@ function createLayer(doc: Document, attribute: string): HTMLElement { } /** - * The element that holds a source's spot: an `li` in a list, so the list - * keeps only `li` children (HTML's content model for `ul`, `ol` and `menu`), - * and a `span` elsewhere. + * The element that holds a source's spot: an `li` in a list, and a `span` + * elsewhere. HTML lets `ul`, `ol` and `menu` hold only `li` children. */ function placeholderTag(source: HTMLElement): 'li' | 'span' { const parent = source.parentElement?.localName; @@ -533,11 +529,11 @@ function placeholderTag(source: HTMLElement): 'li' | 'span' { } /** - * The placeholder that holds a source's spot in the page while it is lifted: - * empty, hidden, at its laid-out size, with its margins and its place in a - * flex or grid container. It is never a list item itself, so it takes no - * number and the items after it keep theirs, and the page's own rules for - * its tag (an `li`'s minimum height, its padding) never change its size. + * The placeholder that holds a source's spot while it is lifted. It is empty + * and hidden, at the source's laid-out size, margins and place in a flex or + * grid container. It is never a list item, so it takes no number and the + * items after it keep theirs. The page's own rules for its tag, such as an + * `li`'s minimum height or padding, never change its size. */ function placeholderStyle( computed: CSSStyleDeclaration, @@ -677,10 +673,11 @@ export function createLiftFromTrigger(): LiftFromTrigger { } }; - // Every pointer that went down on the layer and is still down (the tint - // while it presents, the hold's shield while it closes), read from the - // document so an inert target hides none; and whether the last one to lift - // still owes its click (a touch's click comes after its pointer's up). + // Every pointer still down that went down on the layer: on the tint as it + // presents, or the shield as it closes. The watch reads them from the + // document, so an inert target hides none. It also knows whether the last + // one to lift still owes its click. A touch's click comes after its + // pointer's up. const watchPointers = (current: LiftState) => { const {layer, waits} = current; const doc = layer.ownerDocument; @@ -908,9 +905,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { } source.setAttribute('popover', 'manual'); const waits = new AbortController(); - // The source grows out of where the press left it into its lifted rect, - // laid out at its own size, so its content scales as UIKit's snapshot - // does. Under Reduce Motion it lands at once and fades in. + // The source grows from where the press left it into its lifted rect. It + // stays laid out at its own size, so its content scales as UIKit's + // snapshot does. Under Reduce Motion it lands at once and fades in. let heldAt: number | null = null; const holdClock = (at: number | null) => { heldAt = at; @@ -937,11 +934,11 @@ export function createLiftFromTrigger(): LiftFromTrigger { ], {duration: 0}, ); - // The shadow rises with the source: it follows the source's path on the - // lift's spring and fades in on its own, from the frame the source starts - // in, as one compositor animation (an animated `::backdrop` of the source - // would restyle and lay out the page on every frame). Under Reduce Motion - // it fades in where the source lands. + // The shadow rises with the source. It follows the source's path on the + // lift's spring and fades in on its own spring, from the source's first + // frame. It is one compositor animation: an animated `::backdrop` of the + // source would restyle and lay out the page on every frame. Under Reduce + // Motion it fades in where the source lands. const rise = playShadow( shadowEl, reduced == null @@ -995,9 +992,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { isSourceLifted: true, }; state = current; - // Taps on the backdrop: only a pointer that went down on the layer lifts - // there (WebKit hands the layer the lift of the finger that opened the - // menu). + // Taps on the backdrop count only for a pointer that went down on the + // layer. WebKit hands the layer the lift of the finger that opened the + // menu. let backdropPointer: number | null = null; const listen = {signal: waits.signal}; layer.addEventListener( @@ -1200,12 +1197,13 @@ export function createLiftFromTrigger(): LiftFromTrigger { current.tint?.cancel(); current.tint = fadeBackdrop(layer, 0, motion.clear, {from: tintFrom}); // The source returns to its place from wherever it is now, with its - // velocity; its shadow follows it back frame for frame (the same start, - // the same velocity along the way back) and fades on its own spring. - // Under Reduce Motion both fade where they are. - // One instant for the shadow's reading and the morph's own, and the - // morph's velocity there (from the rect it presents a millisecond - // before: the morph keeps its own clock, synced to its animations'). + // velocity. Its shadow follows it back frame for frame, with the same + // start and velocity, and fades on its own spring. Under Reduce Motion + // both fade where they are. + // The shadow and the morph read one instant, and the morph's velocity + // there. That velocity comes from the rect the morph presents a + // millisecond before. The morph keeps its own clock, synced to its + // animations. const at = performance.now(); current.holdClock(at - 1); const before = current.morph.presentedRect() ?? lifted; @@ -1261,9 +1259,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { }); } }); - // The close holds the layer: nothing reaches the page under it until the - // source is back, the surface's exit is done and every press on the - // layer has lifted. + // The close holds the layer, so nothing reaches the page under it. The + // hold ends when the source is back, the surface's exit is done and every + // press has lifted. const ended = settled.then(async () => current.untilPointersLift()); current.releaseHold?.(); current.releaseHold = holdInput(layer, { @@ -1292,8 +1290,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { } /** - * Sources a copy hides: how many copies hold each, and the visibility it had - * inline before the first, which it gets back when the last drops. + * Sources a copy hides: how many copies hold each, and its inline visibility + * before the first. A source gets that visibility back when its last copy + * drops. */ const hiddenSources = new WeakMap< HTMLElement, @@ -1347,10 +1346,11 @@ function pictureOf(source: HTMLElement): string { /** * Lifts a copy of `source`'s picture into `host` for a zoom, the lift's one - * transient copy: one image laid out at the source's box (aspect fill, its corners), inert and hidden from assistive - * technology, while the source hides where it stands. The caller moves the - * copy on the rect morph and drops it at the landing. Null, with nothing - * changed, for a source that is not in the page or has no box. + * transient copy. The copy is one image at the source's box, with aspect fill + * and its corners. It is inert and hidden from assistive technology, and the + * source hides where it stands. The caller moves the copy on the rect morph + * and drops it at the landing. Null, with nothing changed, for a source that + * is not in the page or has no box. */ export function liftCopy( source: HTMLElement, diff --git a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts index b1101df78cf22..eb5a5b9601497 100644 --- a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts @@ -3,9 +3,9 @@ /** * @file liftFromTriggerGeometry.test.ts * @input vitest, the lift geometry - * @output Checks how far a source grows (the cap, the points on its larger - * side, the viewport's width), where it lands inside the gutter, and which - * side of it a surface takes, in either direction + * @output Checks how far a source grows: the cap, the points on its larger + * side and the viewport's width. It also checks where it lands inside the + * gutter, and a surface's side in either direction * @position Unit tests of packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts; a * surface's own numbers (UIKit's, for ContextMenu) are tested with it */ diff --git a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts index 5bf3f7129f0e4..6e66019977ba2 100644 --- a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts @@ -4,9 +4,8 @@ * @file liftFromTriggerGeometry.ts * @input A source's box, the viewport and the layer runtime's gutter, and * the caller's scale rule and gap - * @output liftFromTriggerScale, liftFromTriggerRect and surfacePlacement: - * how far a lifted source grows, where it lands inside the gutter, and - * which side of it a surface (a menu) takes + * @output liftFromTriggerScale, liftFromTriggerRect and surfacePlacement: a + * lifted source's growth, its place inside the gutter, and a surface's side * @position The geometry of the lift presentation (liftFromTrigger.ts); * internal to core. A source grows about its center by the caller's rule, * as UIKit's preview platter does, then moves inside the gutter @@ -17,10 +16,10 @@ import type {MorphRect} from '../motion/rectMorph'; /** - * The layer runtime's viewport gutter on each edge, CSS px - * (Layer/layerViewportInset.stylex.ts): the spacing step or the - * edge's safe-area inset, whichever is larger, plus the inset an app declares - * for a bar floating over that edge. + * The layer runtime's viewport gutter on each edge, in CSS px + * (Layer/layerViewportInset.stylex.ts). It is the spacing step or the edge's + * safe-area inset, whichever is larger. It adds the inset an app declares for + * a bar over that edge. */ export interface LiftFromTriggerGutter { readonly top: number; @@ -55,8 +54,8 @@ export interface SurfacePlacement { /** * The factor a `width` × `height` source grows by: up to `rule.maxScale`, by - * `rule.scaleUpPoints` on its larger side, and never wider than the viewport - * less its gutter (which can make it smaller than 1). + * `rule.scaleUpPoints` on its larger side. It is never wider than the viewport + * less its gutter, which can make the factor less than 1. */ export function liftFromTriggerScale( width: number, @@ -111,9 +110,9 @@ export function liftFromTriggerRect( /** * A surface's place: below the lifted source when `surfaceHeight` fits - * between it, `gap` and the bottom gutter, else above; centered on the - * source, or flush with the source's edge when the source is held against a - * side of the viewport. + * between it, `gap` and the bottom gutter, else above. It centers on the + * source, or sits flush with the source's edge when the source is held against + * a side of the viewport. */ export function surfacePlacement( lifted: MorphRect, From 96ef39516d8f9cddb25d3e9b0d8e48bf25740456 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 23:57:39 -0800 Subject: [PATCH 33/65] test(liftFromTrigger): a tall source fits between the gutters A source taller than the viewport less its top and bottom gutters landed past the bottom gutter, and a surface with no room above or below was still placed above. Red: the scale ignores the usable height, and placement never reports that neither side fits. --- .../liftFromTriggerGeometry.test.ts | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts index eb5a5b9601497..3cc4e4860f066 100644 --- a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.test.ts @@ -44,6 +44,13 @@ describe('liftFromTriggerScale', () => { ); }); + it('shrinks a source taller than the viewport less its top and bottom gutters', () => { + expect(liftFromTriggerScale(300, 900, VIEWPORT, RULE)).toBeCloseTo( + 738 / 900, + 10, + ); + }); + it('leaves an empty source alone', () => { expect(liftFromTriggerScale(0, 0, VIEWPORT, RULE)).toBe(1); }); @@ -86,6 +93,16 @@ describe('liftFromTriggerRect', () => { ); expect(bottom.y + bottom.height).toBeCloseTo(820, 10); }); + + it('keeps a source taller than the room between the gutters inside both', () => { + const tall = liftFromTriggerRect( + {x: 51, y: 0, width: 300, height: 900}, + VIEWPORT, + RULE, + ); + expect(tall.y).toBeCloseTo(82, 10); + expect(tall.y + tall.height).toBeCloseTo(820, 10); + }); }); describe('surfacePlacement', () => { @@ -99,7 +116,12 @@ describe('surfacePlacement', () => { }); it('goes above where it does not fit below', () => { - expect(surfacePlacement(middle, 400, VIEWPORT, 16).side).toBe('above'); + const low = {...middle, y: 600}; + expect(surfacePlacement(low, 400, VIEWPORT, 16).side).toBe('above'); + }); + + it('reports that neither side fits when the surface is taller than the room above and below', () => { + expect(surfacePlacement(middle, 400, VIEWPORT, 16).side).toBe('none'); }); it('is flush with the edge the source is held against, and the sides swap in a right-to-left page', () => { From da70e021860de21d8756c099551219f39b7ce12c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 23:59:15 -0800 Subject: [PATCH 34/65] fix(liftFromTrigger): the lift fits between the gutters on both axes A lifted source is never taller than the viewport less its top and bottom gutters, as it is never wider. A surface goes above only when it fits under the top gutter; with room on neither side, placement answers `none` and the layer runtime's own fallback places it. --- .../liftFromTriggerGeometry.ts | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts index 6e66019977ba2..a39c2389c83f8 100644 --- a/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts +++ b/packages/core/src/liftFromTrigger/liftFromTriggerGeometry.ts @@ -48,14 +48,18 @@ export interface LiftFromTriggerScaleRule { /** Where a surface sits against the lifted source. */ export interface SurfacePlacement { - readonly side: 'above' | 'below'; + /** + * `none` when the surface fits on neither side: the caller then leaves it to + * the layer runtime's own fallback. + */ + readonly side: 'above' | 'below' | 'none'; readonly alignment: 'start' | 'center' | 'end'; } /** * The factor a `width` × `height` source grows by: up to `rule.maxScale`, by - * `rule.scaleUpPoints` on its larger side. It is never wider than the viewport - * less its gutter, which can make the factor less than 1. + * `rule.scaleUpPoints` on its larger side. It is never wider or taller than + * the viewport less its gutters, which can make the factor less than 1. */ export function liftFromTriggerScale( width: number, @@ -67,11 +71,19 @@ export function liftFromTriggerScale( if (side <= 0) { return 1; } + const {gutter} = viewport; const fitsWidth = - width > 0 - ? (viewport.width - 2 * viewport.gutter.inline) / width + width > 0 ? (viewport.width - 2 * gutter.inline) / width : Infinity; + const fitsHeight = + height > 0 + ? (viewport.height - gutter.top - gutter.bottom) / height : Infinity; - return Math.min(rule.maxScale, (side + rule.scaleUpPoints) / side, fitsWidth); + return Math.min( + rule.maxScale, + (side + rule.scaleUpPoints) / side, + fitsWidth, + fitsHeight, + ); } /** @@ -110,9 +122,10 @@ export function liftFromTriggerRect( /** * A surface's place: below the lifted source when `surfaceHeight` fits - * between it, `gap` and the bottom gutter, else above. It centers on the - * source, or sits flush with the source's edge when the source is held against - * a side of the viewport. + * between it, `gap` and the bottom gutter. Else it goes above, when it fits + * under the top gutter. With room on neither side it answers `none`. It + * centers on the source, or sits flush with the source's edge when the source + * is held against a side of the viewport. */ export function surfacePlacement( lifted: MorphRect, @@ -122,10 +135,9 @@ export function surfacePlacement( ): SurfacePlacement { const {gutter} = viewport; const bottom = viewport.height - gutter.bottom; - const side = - lifted.y + lifted.height + gap + surfaceHeight <= bottom - ? 'below' - : 'above'; + const fitsBelow = lifted.y + lifted.height + gap + surfaceHeight <= bottom; + const fitsAbove = lifted.y - gap - surfaceHeight >= gutter.top; + const side = fitsBelow ? 'below' : fitsAbove ? 'above' : 'none'; const epsilon = 0.5; const atLeft = lifted.x <= gutter.inline + epsilon; const atRight = From 67116fb07b07be79cfa15cb3e72e02c32157712d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:03:49 -0800 Subject: [PATCH 35/65] test(liftFromTrigger): a pinch on the lifted backdrop zooms the page While a row is lifted, a two-finger pinch on the lift layer must zoom the page, tap nothing and reach nothing beneath. Red in Chromium: the layer's `touch-action: none` keeps the page at scale 1. WebKit skips, as the input hold's pinch case does: it pinch-zooms from injected touches only in Mobile Safari on the simulator. --- ...iftFromTrigger.interaction.browser.spec.ts | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index ef993b7400ed1..5c5e5c847920e 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -18,6 +18,7 @@ import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import {pinch, touchDriver} from '@astryxdesign/interaction-harness'; import {build, type Plugin} from 'esbuild'; // The page's `window.__lift`. import type {LiftFixture} from './liftFromTrigger.fixture'; @@ -607,6 +608,53 @@ test('a tap while the row and the menu grow reaches nothing; one on the backdrop await page.evaluate(() => window.__lift.dispose()); }); +test('a pinch on the backdrop while a row is lifted zooms the page, and it neither taps the backdrop nor reaches the page (spec:AST-094 FR10, FR35)', async ({ + page, + browserName, +}) => { + test.skip( + browserName === 'webkit', + 'needs pinch-zoom from injected touches (Mobile Safari on the simulator)', + ); + await open(page); + const driver = await touchDriver(page); + // The lift settles first: the row at its lifted width, the tint risen. + const settled = await page.evaluate(async () => { + const result = window.__lift.lift('row2', 0.2); + const row = document.getElementById('row2'); + const layer = document.querySelector('[data-lift]'); + if (result == null || row == null || layer == null) { + return 'no lift'; + } + for (let frame = 0; frame < 120; frame++) { + await new Promise(resolve => requestAnimationFrame(resolve)); + const width = row.getBoundingClientRect().width; + const tint = Number(getComputedStyle(layer, '::backdrop').opacity); + if (Math.abs(width - result.lifted.width) < 0.5 && tint > 0.999) { + return 'settled'; + } + } + return 'the lift did not settle within 120 frames'; + }); + expect(settled).toBe('settled'); + const scale = async () => + page.evaluate(() => window.visualViewport?.scale ?? 1); + expect(await scale()).toBe(1); + await driver.play( + pinch({ + center: {x: 180, y: 700}, + fromDistance: 60, + toDistance: 220, + durationMs: 200, + }), + ); + await expect.poll(scale).toBeGreaterThan(1.2); + const log = await page.evaluate(() => ({...window.__lift.log})); + expect(log.backdropTaps).toBe(0); + expect(log.clicks).not.toContain('page'); + await page.evaluate(() => window.__lift.dispose()); +}); + test("a zoom's copy lifts into the viewer at the thumbnail's box, where the viewer's stacking puts it under the photo, while the thumbnail hides in place; one element more", async ({ page, }) => { From ff7e46881c062ec3242f0fdd36af188d874e54dd Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:03:49 -0800 Subject: [PATCH 36/65] fix(liftFromTrigger): the lift layer keeps the page's pinch-zoom The layer takes `touch-action: pinch-zoom`, as the input hold's shield does: a one-finger pan still scrolls nothing under the lift, and a pinch zooms the page. --- packages/core/src/liftFromTrigger/liftFromTrigger.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index a9d5787eec270..4789108f61d84 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -512,7 +512,9 @@ function createLayer(doc: Document, attribute: string): HTMLElement { color: 'inherit', overflow: 'visible', pointerEvents: 'auto', - touchAction: 'none', + // A one-finger pan scrolls nothing under the lift, but a pinch still + // zooms the page. + touchAction: 'pinch-zoom', }); return layer; } From 9e7b0b4039ea6b6935e2b540d217574f9ab5acca Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:07:30 -0800 Subject: [PATCH 37/65] test(liftFromTrigger): a drop mid-rise turns the tint with its velocity A drop while the tint still rises must keep the tint's velocity, so the tint rises a little past where the drop found it before it clears. Red in both engines: the clear restarts from rest at the opacity shown, and the tint falls from the first frame after the drop. --- ...iftFromTrigger.interaction.browser.spec.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 5c5e5c847920e..5f8247e5160a4 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -319,6 +319,42 @@ test('the tint clears from what it shows when the row drops, with no jump to cle await page.evaluate(() => window.__lift.dispose()); }); +test('a drop while the tint rises turns it around with its velocity: it keeps rising a little before it clears (spec:AST-094 FR6)', async ({ + page, +}) => { + await open(page); + const tint = await page.evaluate(async () => { + const frame = async () => + new Promise(resolve => requestAnimationFrame(() => resolve())); + const shown = () => { + const layer = document.querySelector('[data-lift]'); + return layer == null + ? -1 + : Number(getComputedStyle(layer, '::backdrop').opacity); + }; + window.__lift.lift('row2', 0.8); + // WebKit shows the stylesheet's opacity until the rise's first frame. + let rising = -1; + for (let i = 0; i < 60 && !(rising > 0.1 && rising < 0.5); i++) { + await frame(); + rising = shown(); + } + window.__lift.drop(); + const after: number[] = []; + for (let i = 0; i < 8; i++) { + await frame(); + after.push(shown()); + } + return {rising, after}; + }); + const detail = JSON.stringify(tint); + expect(tint.rising, detail).toBeGreaterThan(0.05); + expect(tint.rising, detail).toBeLessThan(0.6); + // Still moving up at the drop, it rises past where the drop found it. + expect(Math.max(...tint.after), detail).toBeGreaterThan(tint.rising + 0.03); + await page.evaluate(() => window.__lift.dispose()); +}); + test('every motion the lift plays, the menu’s growth and close included, is translate, scale, transform or opacity (spec:AST-094 FR5)', async ({ page, }) => { From 917d51d86c5f962400ee4f2b0b4586cb94cbc9bd Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:14:23 -0800 Subject: [PATCH 38/65] fix(liftFromTrigger): the tint fades on the animator's backdrop channel The tint is the opacity of the layer's `::backdrop` on its own motion engine in `pseudoElement` mode, in place of keyframes the lift sampled itself. A drop while the tint rises now turns it with its velocity, and Reduce Motion is the animator's, as for every other motion of the lift. The backdrop's color stays held by its own animation. The tint-clear proof reads what the backdrop shows: a risen tint holds no animation. --- packages/core/src/liftFromTrigger/README.md | 3 +- ...iftFromTrigger.interaction.browser.spec.ts | 6 +- .../src/liftFromTrigger/liftFromTrigger.ts | 129 +++++------------- 3 files changed, 41 insertions(+), 97 deletions(-) diff --git a/packages/core/src/liftFromTrigger/README.md b/packages/core/src/liftFromTrigger/README.md index 1099323b95e87..643c039400c7b 100644 --- a/packages/core/src/liftFromTrigger/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -56,7 +56,8 @@ up the page has one element more. Every motion is `translate`, `scale` or `opacity` on the compositor (`spec:AST-094` FR5): the trigger, its shadow and the surface on the rect morph, which continues an interrupted motion with the velocity on screen (FR6); the -tint as a spring-sampled Web Animation of the layer's `::backdrop`. A +tint on the animator, as the opacity of the layer's `::backdrop`, so a drop +while it rises turns it with its velocity too. A tap or a drag that lands while the lift and the surface grow reaches nothing (FR35). The close holds the layer until the trigger is back, the surface's exit is done and every press on the layer has lifted. Its timers and diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 5f8247e5160a4..37cc868d56ea2 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -306,7 +306,11 @@ test('the tint clears from what it shows when the row drops, with no jump to cle .getKeyframes() .map(frame => Number(frame.opacity)), ); - const shown = fades().at(-1)?.at(-1) ?? -1; + // A risen tint holds no animation: the stylesheet shows it. + const shown = + layer == null + ? -1 + : Number(getComputedStyle(layer, '::backdrop').opacity); window.__lift.drop(); const clear = fades().at(-1) ?? []; return {shown, from: clear[0] ?? -1, to: clear.at(-1) ?? -1}; diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 4789108f61d84..fcb63490512e0 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -20,7 +20,11 @@ import {placeLayerExitCopy} from '../Layer/layerExitCopy'; import {layerInsetProperties} from '../Layer/layerInset'; import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import {holdInput} from '../Layer/inputHold'; -import type {MotionHandle} from '../motion/animator'; +import { + createMotionEngine, + type Animator, + type MotionHandle, +} from '../motion/animator'; import {progressCurve} from '../motion/progress'; import { createRectMorph, @@ -31,12 +35,7 @@ import { } from '../motion/rectMorph'; import {reducedMotionFade} from '../motion/reducedMotion'; import {resolveMotion} from '../motion/resolveMotion'; -import { - SETTLING_EPSILON, - solveSpring, - toSpring, - type SpringDescription, -} from '../motion/spring'; +import type {SpringDescription} from '../motion/spring'; import { liftFromTriggerRect, type LiftFromTriggerScaleRule, @@ -226,7 +225,13 @@ interface LiftState { /** The layer's own waits and listeners, released with it. */ readonly waits: AbortController; untilPointersLift: () => Promise; - tint: Animation | null; + /** + * The tint's animator: the opacity of the layer's `::backdrop`. The + * stylesheet shows the backdrop opaque, so a risen tint holds nothing. + */ + readonly tints: Animator; + /** The tint's fade on `tints`. */ + tint: MotionHandle | null; surface: LiftedSurface | null; releaseGrowHold: (() => void) | null; releaseHold: (() => void) | null; @@ -265,29 +270,6 @@ function restore(element: HTMLElement, saved: SavedStyle): void { } } -/** Web Animation keyframes along `spring` from 0 to 1, sampled at 60 Hz. */ -function springKeyframes( - element: Element, - spring: SpringDescription, - frame: (progress: number) => Keyframe, -): {keyframes: Keyframe[]; duration: number} { - const curve = solveSpring(toSpring(resolveMotion(element, spring)), { - from: 0, - to: 1, - }); - const seconds = Math.max(curve.settleTime(SETTLING_EPSILON), 1 / 60); - const steps = Math.max(2, Math.ceil(seconds * 60)); - const keyframes: Keyframe[] = []; - for (let i = 0; i <= steps; i++) { - const t = (i / steps) * seconds; - keyframes.push({ - ...frame(i === steps ? 1 : curve.value(t)), - offset: i / steps, - }); - } - return {keyframes, duration: seconds * 1000}; -} - /** * Web Animation keyframes for a box laid out on `box`. It travels from * `from` to `to` on `travel`, starting at progress velocity `velocity`, as the @@ -429,64 +411,23 @@ function resolvedMotion( }; } -/** Plays `keyframes` on `element`'s `::backdrop`, holding the end. */ -function animateBackdrop( +/** Holds `color` as the background of `element`'s `::backdrop`. */ +function holdBackdropColor( element: HTMLElement, - keyframes: Keyframe[], - options: KeyframeAnimationOptions, + color: string, ): Animation | null { if (typeof element.animate !== 'function') { return null; } try { - return element.animate(keyframes, { - fill: 'forwards', - ...options, - pseudoElement: '::backdrop', - }); - } catch { - // No `::backdrop` animations: the lift shows without its decoration. - return null; - } -} - -/** The `::backdrop` opacity `element` shows now, or `fallback`. */ -function backdropOpacity(element: HTMLElement, fallback: number): number { - try { - const shown = Number.parseFloat( - getComputedStyle(element, '::backdrop').opacity, + return element.animate( + [{backgroundColor: color}, {backgroundColor: color}], + {duration: 0, fill: 'forwards', pseudoElement: '::backdrop'}, ); - return Number.isFinite(shown) ? shown : fallback; } catch { - return fallback; - } -} - -/** - * Fades `element`'s `::backdrop` to `to` on `spring`, from `from` or what it - * shows; `reduced` is the Reduce Motion fade when read already. Opacity - * alone, so the compositor plays it. - */ -function fadeBackdrop( - element: HTMLElement, - to: number, - spring: SpringDescription, - { - from = backdropOpacity(element, to === 1 ? 0 : 1), - reduced = reducedMotionFade(element), - }: {from?: number; reduced?: ReturnType} = {}, -): Animation | null { - if (reduced != null) { - return animateBackdrop( - element, - [{opacity: String(from)}, {opacity: String(to)}], - {duration: reduced.duration, easing: reduced.easing}, - ); + // No `::backdrop` animations: the lift shows without its tint. + return null; } - const {keyframes, duration} = springKeyframes(element, spring, p => ({ - opacity: String(from + (to - from) * p), - })); - return animateBackdrop(element, keyframes, {duration}); } /** @@ -656,7 +597,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { current.releaseHold?.(); current.releaseHold = null; current.waits.abort(); - current.tint?.cancel(); + current.tints.dispose(); current.tint = null; current.layerFill?.cancel(); const {layer} = current; @@ -917,8 +858,14 @@ export function createLiftFromTrigger(): LiftFromTrigger { const morph = createRectMorph(source, { now: () => heldAt ?? performance.now(), }); - // The layer first: the source shows above its tint. + // The layer first: the source shows above its tint. The popover makes + // its `::backdrop` new, so the tint starts clear in the same task. + const tints = createMotionEngine(layer, { + pseudoElement: '::backdrop', + base: {opacity: 1}, + }); layer.showPopover(); + tints.set({opacity: 0}); source.showPopover(); holdClock(performance.now()); const growing = morph.present( @@ -928,14 +875,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { ); holdClock(null); // The tint: the layer's `::backdrop`, its color held there. - const layerFill = animateBackdrop( - layer, - [ - {backgroundColor: tint, opacity: '0'}, - {backgroundColor: tint, opacity: '0'}, - ], - {duration: 0}, - ); + const layerFill = holdBackdropColor(layer, tint); // The shadow rises with the source. It follows the source's path on the // lift's spring and fades in on its own spring, from the source's first // frame. It is one compositor animation: an animated `::backdrop` of the @@ -987,7 +927,8 @@ export function createLiftFromTrigger(): LiftFromTrigger { holdClock, waits, untilPointersLift: async () => {}, - tint: fadeBackdrop(layer, 1, motion.lift, {from: 0, reduced}), + tints, + tint: tints.animate({opacity: 1}, {spring: motion.lift}), surface: null, releaseGrowHold: null, releaseHold: null, @@ -1194,10 +1135,8 @@ export function createLiftFromTrigger(): LiftFromTrigger { } releaseGrowHold(current); const {layer, motion, source, sourceRect, lifted} = current; - // The tint clears from what it shows now, read before its rise stops. - const tintFrom = backdropOpacity(layer, 1); - current.tint?.cancel(); - current.tint = fadeBackdrop(layer, 0, motion.clear, {from: tintFrom}); + // The tint clears from what it shows now, with its velocity. + current.tint = current.tints.animate({opacity: 0}, {spring: motion.clear}); // The source returns to its place from wherever it is now, with its // velocity. Its shadow follows it back frame for frame, with the same // start and velocity, and fades on its own spring. Under Reduce Motion From 50f150c928b4420d44be57e8caf5257140374a3d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 00:23:50 -0800 Subject: [PATCH 39/65] refactor(liftFromTrigger): the shadow rides a rect morph of its own The shadow played keyframes the lift sampled itself, where the README says it rides a rect morph. It now plays the source's path on `createRectMorph`, on the source's clock, with its fade on its own spring as the morph's `fade` timing. Its drop is the morph's dismissal from the rect on screen, with its velocity. Reduce Motion is the animator's. The frame-for-frame proof passes unchanged in both engines. --- .../src/liftFromTrigger/liftFromTrigger.ts | 181 ++++-------------- 1 file changed, 38 insertions(+), 143 deletions(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index fcb63490512e0..9d184f92e3b01 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -25,7 +25,6 @@ import { type Animator, type MotionHandle, } from '../motion/animator'; -import {progressCurve} from '../motion/progress'; import { createRectMorph, lerpPath, @@ -216,10 +215,11 @@ interface LiftState { * is. It follows the source frame for frame and fades on its own spring. */ readonly shadow: HTMLElement; - shadowAnimation: Animation | null; + /** The shadow's rect morph, on the source's path and clock. */ + readonly shadowMorph: RectMorph; /** - * Holds the source morph's clock at one instant (null lets it run), so the - * shadow reads the motion at the very moment the morph does. + * Holds the clock of both morphs at one instant (null lets it run), so the + * shadow starts each motion where the source does. */ readonly holdClock: (at: number | null) => void; /** The layer's own waits and listeners, released with it. */ @@ -270,70 +270,6 @@ function restore(element: HTMLElement, saved: SavedStyle): void { } } -/** - * Web Animation keyframes for a box laid out on `box`. It travels from - * `from` to `to` on `travel`, starting at progress velocity `velocity`, as the - * rect morph does. Its opacity goes from `fade[0]` to `fade[1]` on - * `fadeSpring`. The keyframes sample both at 60 Hz until both settle. The - * result is one compositor animation of `transform` and `opacity`, frame for - * frame with the source's morph. - */ -function shadowKeyframes( - box: MorphRect, - from: MorphRect, - to: MorphRect, - travel: SpringDescription | null, - fade: readonly [number, number], - fadeSpring: SpringDescription, - velocity = 0, -): {keyframes: Keyframe[]; duration: number} { - const move = travel == null ? null : progressCurve(travel, {velocity}); - const opacity = progressCurve(fadeSpring); - const seconds = Math.max(move?.duration ?? 0, opacity.duration, 1 / 60); - const steps = Math.max(2, Math.ceil(seconds * 60)); - const keyframes: Keyframe[] = []; - for (let i = 0; i <= steps; i++) { - const t = (i / steps) * seconds; - const p = i === steps || move == null ? 1 : move.at(t); - const q = i === steps ? 1 : opacity.at(t); - const rect = { - x: from.x + (to.x - from.x) * p, - y: from.y + (to.y - from.y) * p, - width: from.width + (to.width - from.width) * p, - }; - const scale = box.width > 0 ? rect.width / box.width : 1; - keyframes.push({ - transform: `translate(${(rect.x - box.x).toFixed(3)}px, ${(rect.y - box.y).toFixed(3)}px) scale(${scale.toFixed(5)})`, - opacity: String( - Math.min(Math.max(fade[0] + (fade[1] - fade[0]) * q, 0), 1), - ), - offset: i / steps, - }); - } - return {keyframes, duration: seconds * 1000}; -} - -/** Plays `keyframes` on `element`, or only their ends under Reduce Motion. */ -function playShadow( - element: HTMLElement, - {keyframes, duration}: {keyframes: Keyframe[]; duration: number}, - reduced: ReturnType, -): Animation | null { - if (typeof element.animate !== 'function') { - return null; - } - return element.animate( - reduced == null - ? keyframes - : [keyframes[0], keyframes[keyframes.length - 1]], - { - duration: reduced?.duration ?? duration, - easing: reduced?.easing ?? 'linear', - fill: 'forwards', - }, - ); -} - /** * The radius of the shape `source` shows: its own, or that of its only * element child when that child fills it. @@ -566,8 +502,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { } current.isSourceLifted = false; const {source} = current; - current.shadowAnimation?.cancel(); - current.shadowAnimation = null; + current.shadowMorph.dispose(); current.morph.dispose(); if (source.matches(':popover-open')) { source.hidePopover(); @@ -735,7 +670,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { const direction = computed.direction === 'rtl' ? 'rtl' : 'ltr'; const radius = shapeRadius(source); const motion = resolvedMotion(source, options.motion); - const reduced = reducedMotionFade(source); // The tint, the shadow and the layer runtime's gutter, with the inset an // app declares, resolved where the source is. const probed = probe(source, { @@ -855,9 +789,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { const holdClock = (at: number | null) => { heldAt = at; }; - const morph = createRectMorph(source, { - now: () => heldAt ?? performance.now(), - }); + const now = () => heldAt ?? performance.now(); + const morph = createRectMorph(source, {now}); + const shadowMorph = createRectMorph(shadowEl, {now}); // The layer first: the source shows above its tint. The popover makes // its `::backdrop` new, so the tint starts clear in the same task. const tints = createMotionEngine(layer, { @@ -873,40 +807,22 @@ export function createLiftFromTrigger(): LiftFromTrigger { {spring: motion.lift}, {crossfadeAs: 'entrance'}, ); + // The shadow rises with the source, frame for frame: the same path, + // spring and clock. It fades in on its own spring. It is a box in the + // layer, because an animated `::backdrop` of the source would restyle and + // lay out the page on every frame. + shadowMorph.present( + lerpPath(from, lifted, { + box: sourceRect, + scale: 'uniform', + opacity: [0, 1], + }), + {spring: motion.lift}, + {fade: {spring: motion.shadowIn}, crossfadeAs: 'entrance'}, + ); holdClock(null); // The tint: the layer's `::backdrop`, its color held there. const layerFill = holdBackdropColor(layer, tint); - // The shadow rises with the source. It follows the source's path on the - // lift's spring and fades in on its own spring, from the source's first - // frame. It is one compositor animation: an animated `::backdrop` of the - // source would restyle and lay out the page on every frame. Under Reduce - // Motion it fades in where the source lands. - const rise = playShadow( - shadowEl, - reduced == null - ? shadowKeyframes( - sourceRect, - from, - lifted, - motion.lift, - [0, 1], - motion.shadowIn, - ) - : shadowKeyframes( - sourceRect, - lifted, - lifted, - null, - [0, 1], - motion.shadowIn, - ), - reduced, - ); - void growing.started.then(at => { - if (rise != null && current.shadowAnimation === rise) { - rise.startTime = at; - } - }); const current: LiftState = { generation, options, @@ -923,7 +839,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { growing, layerFill, shadow: shadowEl, - shadowAnimation: rise, + shadowMorph, holdClock, waits, untilPointersLift: async () => {}, @@ -1138,43 +1054,22 @@ export function createLiftFromTrigger(): LiftFromTrigger { // The tint clears from what it shows now, with its velocity. current.tint = current.tints.animate({opacity: 0}, {spring: motion.clear}); // The source returns to its place from wherever it is now, with its - // velocity. Its shadow follows it back frame for frame, with the same - // start and velocity, and fades on its own spring. Under Reduce Motion - // both fade where they are. - // The shadow and the morph read one instant, and the morph's velocity - // there. That velocity comes from the rect the morph presents a - // millisecond before. The morph keeps its own clock, synced to its - // animations. - const at = performance.now(); - current.holdClock(at - 1); - const before = current.morph.presentedRect() ?? lifted; - current.holdClock(at); - const presented = current.morph.presentedRect() ?? lifted; - const shadowEl = current.shadow; - const shownOpacity = - Number.parseFloat( - shadowEl.ownerDocument.defaultView?.getComputedStyle(shadowEl) - .opacity ?? '', - ) || 0; - current.shadowAnimation?.cancel(); - const reducedFade = reducedMotionFade(source); - // That velocity as progress along the way back (from where it is drawn - // to the source's place), as the morph reads it. - const span = presented.width - sourceRect.width; - const widthVelocity = (presented.width - before.width) * 1000; - const backVelocity = Math.abs(span) > 1e-6 ? -widthVelocity / span : 0; - current.shadowAnimation = playShadow( - shadowEl, - shadowKeyframes( - sourceRect, - presented, - reducedFade == null ? sourceRect : presented, - reducedFade == null ? motion.drop : null, - [shownOpacity, 0], - motion.shadowOut, - backVelocity, - ), - reducedFade, + // velocity. Its shadow follows it back frame for frame: the same instant, + // path and spring. It fades on its own spring. Under Reduce Motion both + // fade where they are. + current.holdClock(performance.now()); + current.shadowMorph.dismiss( + lerpPath(sourceRect, lifted, { + box: sourceRect, + scale: 'uniform', + opacity: [0, 1], + }), + {spring: motion.drop}, + { + target: current.shadow, + fade: {spring: motion.shadowOut}, + crossfadeAs: 'exit', + }, ); const returning = current.morph.dismiss( lerpPath(sourceRect, lifted, {box: sourceRect, scale: 'uniform'}), From 87b4151e9619aa440abcbb660b73a1c16685f9ae Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 01:16:37 -0800 Subject: [PATCH 40/65] test(liftFromTrigger): a dropped row's margin returns with no transition The lift zeroes a row's own margin, and the drop must put it back at once, with none of the row's transitions running. The proof guards the style flush that ends the restore: with the flush removed, the margin's transition runs, as that mutation shows. Page script cannot count layouts, so no proof shows the extra layout itself. --- ...iftFromTrigger.interaction.browser.spec.ts | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 37cc868d56ea2..2fc9826f45a0c 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -359,6 +359,47 @@ test('a drop while the tint rises turns it around with its velocity: it keeps ri await page.evaluate(() => window.__lift.dispose()); }); +test('a drop puts the row back with no transition running, whatever transitions the row has: its own margin returns at once', async ({ + page, +}) => { + await open(page); + const running = await page.evaluate(async () => { + const frame = async () => + new Promise(resolve => requestAnimationFrame(() => resolve())); + const row = document.getElementById('row2') as HTMLElement; + // The lift zeroes the row's margin; the drop puts it back. + row.style.marginLeft = '10px'; + row.style.transition = 'margin-left 1s, translate 1s, scale 1s'; + window.__lift.lift('row2', 0.2); + for (let i = 0; i < 30; i++) { + await frame(); + } + window.__lift.drop(); + let frames = 0; + for (; frames < 180 && window.__lift.isLifted(); frames++) { + await frame(); + } + await frame(); + return { + settled: !window.__lift.isLifted(), + frames, + transitions: row + .getAnimations() + .filter(animation => animation instanceof CSSTransition) + .map(animation => animation.transitionProperty), + transition: row.style.transition, + }; + }); + const detail = JSON.stringify(running); + expect(running.settled, detail).toBe(true); + // The row's own transitions are back, and none of them ran on the return. + expect(running.transition, detail).toBe( + 'margin-left 1s, translate 1s, scale 1s', + ); + expect(running.transitions, detail).toEqual([]); + await page.evaluate(() => window.__lift.dispose()); +}); + test('every motion the lift plays, the menu’s growth and close included, is translate, scale, transform or opacity (spec:AST-094 FR5)', async ({ page, }) => { From 29677fd39e135fb21d74a1064e0cc7caaaca3236 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 8 Nov 2026 01:16:37 -0800 Subject: [PATCH 41/65] fix(liftFromTrigger): the restore flushes style with a non-geometry read `settleSource` read the source's computed `width`, a geometry value, between its restore writes and the next lift's reads. So a lift that replaced another laid the page out twice in one task. It reads `transitionProperty` instead: the restored values still apply before the transitions return, with no layout. --- packages/core/src/liftFromTrigger/liftFromTrigger.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index 9d184f92e3b01..c37b8a8d8cf92 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -511,8 +511,10 @@ export function createLiftFromTrigger(): LiftFromTrigger { restore(source, current.saved); current.placeholder?.remove(); // The restored values apply before the source's own transitions return, - // so none of them animates. - void source.ownerDocument.defaultView?.getComputedStyle(source).width; + // so none of them animates. A style read, not a geometry one, so it lays + // nothing out. + void source.ownerDocument.defaultView?.getComputedStyle(source) + .transitionProperty; const [value, priority] = current.transition; if (value === '') { source.style.removeProperty('transition'); From 5f3626202b9a1d9c442a24dd31b1d15e7a6b2b80 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 9 Nov 2026 19:40:37 -0800 Subject: [PATCH 42/65] fix(liftFromTrigger): the lifted trigger casts no shadow The spec owner asked to drop the lift's shadow, since it made the lift look worse. The lift keeps its zoom, tint, surface placement and backdrop tap, and drops the shadow box with its rect morph, springs and option. The page gains three elements while lifted, not four: the layer, the anchor and the placeholder. The proofs assert no shadow element, and the frame-for-frame shadow proof goes. --- .changeset/lift-module.md | 2 +- packages/core/src/liftFromTrigger/README.md | 15 ++-- .../__tests__/liftFromTrigger.fixture.ts | 4 +- ...iftFromTrigger.interaction.browser.spec.ts | 71 ++++----------- .../liftFromTrigger/liftFromTrigger.test.ts | 12 +-- .../src/liftFromTrigger/liftFromTrigger.ts | 89 +------------------ 6 files changed, 34 insertions(+), 159 deletions(-) diff --git a/.changeset/lift-module.md b/.changeset/lift-module.md index 6d6b6ea44e3c2..bd57749793065 100644 --- a/.changeset/lift-module.md +++ b/.changeset/lift-module.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, four elements while lifted. A zoom from a thumbnail lifts a copy of the thumbnail's picture into the viewer instead, while the thumbnail hides in place. Not exported from the package entry point; no component uses it yet. +[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, three elements while lifted, and no shadow. A zoom from a thumbnail lifts a copy of the thumbnail's picture into the viewer instead, while the thumbnail hides in place. Not exported from the package entry point; no component uses it yet. @vjeux diff --git a/packages/core/src/liftFromTrigger/README.md b/packages/core/src/liftFromTrigger/README.md index 643c039400c7b..e5f598902eddb 100644 --- a/packages/core/src/liftFromTrigger/README.md +++ b/packages/core/src/liftFromTrigger/README.md @@ -24,14 +24,13 @@ or stacking ancestor cuts or covers it, and an empty placeholder after it holds its spot, so the page does not move. In a list the placeholder is an `li` that is not a list item, so the list stays valid and keeps its numbers. The trigger takes no hits while lifted: a tap on it is a tap on the backdrop. -While lifted the page has four +While lifted the page has three elements more, whatever the trigger holds: the lift layer (its `::backdrop` -is the tint); the shadow, a box in the layer that follows the trigger on a -rect morph of its own (an animated `::backdrop` of the trigger would restyle -and lay out the page on every frame); an empty box at the lifted rect for -the surface to be placed against (anchor positioning follows transforms, so -a box inside the trigger would move with it); and the placeholder. The input hold's shield joins while the lift grows and -while it closes: never more than five (`spec:AST-017` FR60, DEC-29). The +is the tint); an empty box at the lifted rect for the surface to be placed +against (anchor positioning follows transforms, so a box inside the trigger +would move with it); and the placeholder. The lifted trigger casts no +shadow. The input hold's shield joins while the lift grows and while it +closes: never more than four (`spec:AST-017` FR60, DEC-29). The exit copy the surface shrinks on is the layer runtime's transient copy. At rest there is nothing. @@ -54,7 +53,7 @@ up the page has one element more. ## Motion Every motion is `translate`, `scale` or `opacity` on the compositor -(`spec:AST-094` FR5): the trigger, its shadow and the surface on the rect morph, +(`spec:AST-094` FR5): the trigger and the surface on the rect morph, which continues an interrupted motion with the velocity on screen (FR6); the tint on the animator, as the opacity of the layer's `::backdrop`, so a drop while it rises turns it with its velocity too. A diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts index 8a30b6ec656fc..a2852ad904f32 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts @@ -52,7 +52,7 @@ declare global { } document.documentElement.style.cssText = - '--color-overlay: rgba(1, 18, 40, 0.4); --shadow-high: 0 8px 24px rgba(0, 0, 0, 0.3); --spacing-4: 16px;'; + '--color-overlay: rgba(1, 18, 40, 0.4); --spacing-4: 16px;'; document.body.style.margin = '0'; document.body.style.font = '16px sans-serif'; const deep = Array.from( @@ -112,8 +112,6 @@ function options(response: number): LiftFromTriggerOptions { lift: spring, drop: spring, clear: spring, - shadowIn: spring, - shadowOut: spring, surfaceIn: spring, surfaceOut: spring, }, diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 2fc9826f45a0c..8b2ef8710f4b4 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -7,7 +7,7 @@ * @output Proof in real engines of the lift and the zoom's copy. A row lifts * into the top layer while a placeholder holds its spot. Every motion is * `translate`, `scale`, `transform` or `opacity`. The menu grows out of the - * press and shrinks back into it on close. The page has at most five more + * press and shrinks back into it on close. The page has at most four more * elements while lifted, and none after the drop. A tap while it grows * reaches nothing. The zoom's copy grows on the rect morph, turns around * and lands in the thumbnail @@ -97,7 +97,7 @@ test('a row lifts itself into the top layer at its lifted rect while one placeho row3: box(document.getElementById('row3')), row4: box(document.getElementById('row4')), placeholder: box(document.querySelector('[data-lift-placeholder]')), - shadow: box(document.querySelector('[data-lift-shadow]')), + hasShadow: document.querySelector('[data-lift-shadow]') != null, isOpen: row.matches(':popover-open'), look: [ style.color, @@ -126,8 +126,8 @@ test('a row lifts itself into the top layer at its lifted rect while one placeho }; expect(lifted.width).toBeCloseTo(361, 3); expectBox(after.row2, [lifted.x, lifted.y, lifted.width, lifted.height]); - // Its shadow lies exactly under it. - expectBox(after.shadow, [lifted.x, lifted.y, lifted.width, lifted.height]); + // It casts no shadow. + expect(after.hasShadow).toBe(false); expectBox(after.placeholder, before.row2); expectBox(after.row1, before.row1); expectBox(after.row3, before.row3); @@ -186,13 +186,12 @@ test('a lifted item of an ordered list leaves the numbers of the items after it page, }) => { await open(page); - // An ordered list with its markers outside, and no tint and no shadow. A - // later item's marker paints the same while an item is lifted, unless its - // number changes. + // An ordered list with its markers outside, and no tint. A later item's + // marker paints the same while an item is lifted, unless its number + // changes. const clip = await page.evaluate(() => { const root = document.documentElement.style; root.setProperty('--color-overlay', 'transparent'); - root.setProperty('--shadow-high', 'none'); const panel = document.querySelector('.panel'); if (panel != null) { panel.style.display = 'none'; @@ -239,46 +238,6 @@ test('a lifted item of an ordered list leaves the numbers of the items after it await page.evaluate(() => window.__lift.dispose()); }); -test('the shadow follows the row on every frame of its lift and of its drop', async ({ - page, -}) => { - await open(page); - // Every animation of the lift, held at the same moment `t` ms in. - const at = async (t: number) => - page.evaluate(time => { - for (const animation of document.getAnimations()) { - animation.pause(); - animation.currentTime = time; - } - const box = (element: Element | null): Box => { - const r = element?.getBoundingClientRect(); - return r == null ? [0, 0, 0, 0] : [r.x, r.y, r.width, r.height]; - }; - return { - row: box(document.getElementById('row2')), - shadow: box(document.querySelector('[data-lift-shadow]')), - }; - }, t); - await page.evaluate(() => window.__lift.lift('row2', 0.2)); - await page.waitForTimeout(50); - for (const t of [30, 90, 180]) { - const {row, shadow} = await at(t); - expectBox(shadow, row); - } - await page.evaluate(() => { - for (const animation of document.getAnimations()) { - animation.finish(); - } - window.__lift.drop(); - }); - await page.waitForTimeout(50); - for (const t of [30, 90]) { - const {row, shadow} = await at(t); - expectBox(shadow, row); - } - await page.evaluate(() => window.__lift.dispose()); -}); - test('the tint clears from what it shows when the row drops, with no jump to clear', async ({ page, }) => { @@ -568,7 +527,7 @@ test('without a press the menu fades in where it rests: opacity only, no travel await page.evaluate(() => window.__lift.dispose()); }); -test('while lifted the page has the layer, the shadow, the anchor and the placeholder more, whatever the row holds, and never more than 5 (AST-017 FR60); a drop leaves the page as it was', async ({ +test('while lifted the page has the layer, the anchor and the placeholder more, whatever the row holds, and never more than 4 (AST-017 FR60); a drop leaves the page as it was', async ({ page, }) => { await open(page); @@ -622,13 +581,13 @@ test('while lifted the page has the layer, the shadow, the anchor and the placeh lifted: window.__lift.isLifted(), }; }); - // A row of 13 elements and a row of 1 add the same 4 once grown: the layer, - // the shadow, the anchor and the placeholder. The hold's shield joins while - // the lift grows. - expect(counts.deep).toBe(5); - expect(counts.shallow).toBe(5); - expect(counts.open).toBe(4); - expect(counts.most).toBeLessThanOrEqual(5); + // A row of 13 elements and a row of 1 add the same 3 once grown: the layer, + // the anchor and the placeholder. The hold's shield joins while the lift + // grows. + expect(counts.deep).toBe(4); + expect(counts.shallow).toBe(4); + expect(counts.open).toBe(3); + expect(counts.most).toBeLessThanOrEqual(4); expect(counts.after).toBe(0); expect(counts.styleAfter).toBe(counts.style); expect(counts.popoverAfter).toBeNull(); diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts index d0db0379ea10b..dcff98c342869 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.test.ts @@ -37,8 +37,6 @@ function options( lift: SPRING, drop: SPRING, clear: SPRING, - shadowIn: SPRING, - shadowOut: SPRING, surfaceIn: SPRING, surfaceOut: SPRING, }, @@ -194,14 +192,15 @@ function expectNoDocumentListeners() { } describe('lift', () => { - it('adds the layer, its shadow and anchor, and one placeholder while lifted, whatever the source holds; the source keeps its place among its siblings', () => { + it('adds the layer, its anchor and one placeholder while lifted, and no shadow, whatever the source holds; the source keeps its place among its siblings', () => { const {source, before} = renderList(); const rest = count(); const lift = createLiftFromTrigger(); const result = lift.lift(source, options()); expect(result).not.toBeNull(); - // 13 elements lifted (the row and its 12), 4 added. - expect(count()).toBe(rest + 4); + // 13 elements lifted (the row and its 12), 3 added. + expect(count()).toBe(rest + 3); + expect(document.querySelector('[data-test-lift-shadow]')).toBeNull(); expect(source.previousElementSibling).toBe(before); const placeholder = source.nextElementSibling as HTMLElement; expect(placeholder.hasAttribute('data-test-lift-placeholder')).toBe(true); @@ -350,7 +349,8 @@ describe('lift', () => { const rest = count(); const lift = createLiftFromTrigger(); lift.lift(source, options()); - expect(count()).toBe(rest + 3); + // The layer and its anchor only. + expect(count()).toBe(rest + 2); lift.dispose(); }); diff --git a/packages/core/src/liftFromTrigger/liftFromTrigger.ts b/packages/core/src/liftFromTrigger/liftFromTrigger.ts index c37b8a8d8cf92..2ed5a51244894 100644 --- a/packages/core/src/liftFromTrigger/liftFromTrigger.ts +++ b/packages/core/src/liftFromTrigger/liftFromTrigger.ts @@ -55,10 +55,6 @@ export interface LiftFromTriggerMotion { readonly drop: SpringDescription; /** The tint clears on it. */ readonly clear: SpringDescription; - /** The shadow rises on it. */ - readonly shadowIn: SpringDescription; - /** The shadow fades on it. */ - readonly shadowOut: SpringDescription; /** A surface grows out of the press on it. */ readonly surfaceIn: SpringDescription; /** A surface shrinks back into the press on it. */ @@ -87,8 +83,6 @@ export interface LiftFromTriggerOptions { readonly release?: () => void; /** The tint, a CSS color resolved where the source is. */ readonly tint?: string; - /** The shadow under the lifted source, a CSS box shadow. */ - readonly shadow?: string; /** The inset an app declares for a bar over an edge (LayerProvider). */ readonly inset?: LayerInset; /** A finger lifted on the backdrop where it went down. */ @@ -210,18 +204,6 @@ interface LiftState { readonly growing: MotionHandle; /** The tint's color, held on the layer's `::backdrop`. */ readonly layerFill: Animation | null; - /** - * The shadow under the source, a box in the layer laid out where the source - * is. It follows the source frame for frame and fades on its own spring. - */ - readonly shadow: HTMLElement; - /** The shadow's rect morph, on the source's path and clock. */ - readonly shadowMorph: RectMorph; - /** - * Holds the clock of both morphs at one instant (null lets it run), so the - * shadow starts each motion where the source does. - */ - readonly holdClock: (at: number | null) => void; /** The layer's own waits and listeners, released with it. */ readonly waits: AbortController; untilPointersLift: () => Promise; @@ -340,8 +322,6 @@ function resolvedMotion( lift: resolve(motion.lift), drop: resolve(motion.drop), clear: resolve(motion.clear), - shadowIn: resolve(motion.shadowIn), - shadowOut: resolve(motion.shadowOut), surfaceIn: resolve(motion.surfaceIn), surfaceOut: resolve(motion.surfaceOut), }; @@ -502,7 +482,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { } current.isSourceLifted = false; const {source} = current; - current.shadowMorph.dispose(); current.morph.dispose(); if (source.matches(':popover-open')) { source.hidePopover(); @@ -670,10 +649,9 @@ export function createLiftFromTrigger(): LiftFromTrigger { ? placeholderStyle(computed, sourceRect) : null; const direction = computed.direction === 'rtl' ? 'rtl' : 'ltr'; - const radius = shapeRadius(source); const motion = resolvedMotion(source, options.motion); - // The tint, the shadow and the layer runtime's gutter, with the inset an - // app declares, resolved where the source is. + // The tint and the layer runtime's gutter, with the inset an app + // declares, resolved where the source is. const probed = probe(source, { ...Object.fromEntries( Object.entries(layerInsetProperties(options.inset)).map( @@ -681,7 +659,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { ), ), 'background-color': options.tint ?? 'var(--color-overlay)', - 'box-shadow': options.shadow ?? 'var(--shadow-high)', 'padding-top': [ `calc(${layerViewportInset.gutterBlockStartFallback})`, `calc(${layerViewportInset.gutterBlockStart})`, @@ -696,7 +673,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { ], }); const tint = probed['background-color']; - const shadow = probed['box-shadow']; const viewport: LiftFromTriggerViewport = { width: doc.documentElement.clientWidth || view?.innerWidth || 0, height: view?.innerHeight ?? doc.documentElement.clientHeight, @@ -712,22 +688,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { options.release?.(); const layer = createLayer(doc, attribute); doc.body.append(layer); - const shadowEl = doc.createElement('span'); - shadowEl.setAttribute(`${attribute}-shadow`, ''); - Object.assign(shadowEl.style, { - position: 'absolute', - left: `${sourceRect.x}px`, - top: `${sourceRect.y}px`, - width: `${sourceRect.width}px`, - height: `${sourceRect.height}px`, - borderRadius: radius, - boxShadow: shadow, - opacity: '0', - pointerEvents: 'none', - // Its keyframes scale about the top-left corner, as the source's do. - transformOrigin: '0 0', - }); - layer.append(shadowEl); const anchor = doc.createElement('span'); anchor.setAttribute(`${attribute}-anchor`, ''); Object.assign(anchor.style, { @@ -787,13 +747,7 @@ export function createLiftFromTrigger(): LiftFromTrigger { // The source grows from where the press left it into its lifted rect. It // stays laid out at its own size, so its content scales as UIKit's // snapshot does. Under Reduce Motion it lands at once and fades in. - let heldAt: number | null = null; - const holdClock = (at: number | null) => { - heldAt = at; - }; - const now = () => heldAt ?? performance.now(); - const morph = createRectMorph(source, {now}); - const shadowMorph = createRectMorph(shadowEl, {now}); + const morph = createRectMorph(source); // The layer first: the source shows above its tint. The popover makes // its `::backdrop` new, so the tint starts clear in the same task. const tints = createMotionEngine(layer, { @@ -803,26 +757,11 @@ export function createLiftFromTrigger(): LiftFromTrigger { layer.showPopover(); tints.set({opacity: 0}); source.showPopover(); - holdClock(performance.now()); const growing = morph.present( lerpPath(from, lifted, {box: sourceRect, scale: 'uniform'}), {spring: motion.lift}, {crossfadeAs: 'entrance'}, ); - // The shadow rises with the source, frame for frame: the same path, - // spring and clock. It fades in on its own spring. It is a box in the - // layer, because an animated `::backdrop` of the source would restyle and - // lay out the page on every frame. - shadowMorph.present( - lerpPath(from, lifted, { - box: sourceRect, - scale: 'uniform', - opacity: [0, 1], - }), - {spring: motion.lift}, - {fade: {spring: motion.shadowIn}, crossfadeAs: 'entrance'}, - ); - holdClock(null); // The tint: the layer's `::backdrop`, its color held there. const layerFill = holdBackdropColor(layer, tint); const current: LiftState = { @@ -840,9 +779,6 @@ export function createLiftFromTrigger(): LiftFromTrigger { morph, growing, layerFill, - shadow: shadowEl, - shadowMorph, - holdClock, waits, untilPointersLift: async () => {}, tints, @@ -1056,29 +992,12 @@ export function createLiftFromTrigger(): LiftFromTrigger { // The tint clears from what it shows now, with its velocity. current.tint = current.tints.animate({opacity: 0}, {spring: motion.clear}); // The source returns to its place from wherever it is now, with its - // velocity. Its shadow follows it back frame for frame: the same instant, - // path and spring. It fades on its own spring. Under Reduce Motion both - // fade where they are. - current.holdClock(performance.now()); - current.shadowMorph.dismiss( - lerpPath(sourceRect, lifted, { - box: sourceRect, - scale: 'uniform', - opacity: [0, 1], - }), - {spring: motion.drop}, - { - target: current.shadow, - fade: {spring: motion.shadowOut}, - crossfadeAs: 'exit', - }, - ); + // velocity. Under Reduce Motion it fades where it is. const returning = current.morph.dismiss( lerpPath(sourceRect, lifted, {box: sourceRect, scale: 'uniform'}), {spring: motion.drop}, {target: source, crossfadeAs: 'exit'}, ); - current.holdClock(null); const exit = current.surface?.dismissing; const settled = Promise.all([returning.finished, exit?.finished]); void settled.then(() => { From d2e52c026da8305d5a5fb50a0747cd1bdf30f4f1 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 9 Nov 2026 19:40:37 -0800 Subject: [PATCH 43/65] test(liftFromTrigger): the growth sample reads its animations at 30 ms The proof that the menu grows out of the press read the menu two frames after it began. One WebKit run under the CI profile drew it at 144 px then, past the 125 px bound, because a late frame let the growth run on. The sample now pauses the menu's own animations 30 ms in, reads the box, and ends the growth, so frame timing cannot move it. --- ...iftFromTrigger.interaction.browser.spec.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts index 8b2ef8710f4b4..868ace6c7c5b4 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.interaction.browser.spec.ts @@ -425,11 +425,27 @@ test('the menu grows out of the press into its box and keeps nothing inline at r await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)), ); - const r = ( - document.getElementById('menu') as HTMLElement - ).getBoundingClientRect(); - return {x: r.x + r.width / 2, y: r.y + r.height / 2, width: r.width}; + // The growth 30 ms in, read from its own animations: a late frame + // cannot move the sample. Then the growth ends at once. + const menu = document.getElementById('menu') as HTMLElement; + const animations = menu.getAnimations(); + for (const animation of animations) { + animation.pause(); + animation.currentTime = 30; + } + const r = menu.getBoundingClientRect(); + for (const animation of animations) { + animation.finish(); + } + return { + x: r.x + r.width / 2, + y: r.y + r.height / 2, + width: r.width, + animations: animations.length, + }; }, press); + // The growth runs on the menu itself, so the sample is 30 ms into it. + expect(early.animations).toBeGreaterThan(0); // Small, and nearer the press than its own center. expect(early.width).toBeLessThan(125); const fromPress = Math.hypot(early.x - press.x, early.y - press.y); From bae645b8e7ab45e972383e51b7245fe74c31805d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 9 Nov 2026 22:02:57 -0800 Subject: [PATCH 44/65] fix(liftFromTrigger): a source lifts at its layout width The lift pinned the source at `offsetWidth` and `offsetHeight`, which round. A source laid out a fraction of a pixel wider than its rounded width, such as a short label in a card, lost that fraction when lifted, and its text wrapped onto a second line past its box. The lift now pins the border box's size from the computed style, which keeps the fraction, and falls back to the offset size for a box with no used size in px. --- .../__tests__/liftFromTrigger.fixture.ts | 1 + ...iftFromTrigger.interaction.browser.spec.ts | 27 +++++++++++++ .../src/liftFromTrigger/liftFromTrigger.ts | 39 +++++++++++++++++-- 3 files changed, 63 insertions(+), 4 deletions(-) diff --git a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts index a2852ad904f32..eed1e23c9c57f 100644 --- a/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts +++ b/packages/core/src/liftFromTrigger/__tests__/liftFromTrigger.fixture.ts @@ -77,6 +77,7 @@ document.body.innerHTML = ` +