Skip to content

Commit da398d0

Browse files
committed
feat(core): one rect morph for touch presentations that grow out of a source rect
Five touch presentations grow a surface out of a source rect and shrink it back, each with its own copy of the math: DropdownMenu's menu, Popover, the context menu's lifted preview, Lightbox's zoom and a sub-menu's parent card. This adds the one shared piece to @astryxdesign/core/motion/experimental, on the animator. - rectMorph.ts: a path names the rect an element shows at each progress (0 on its source, 1 at rest). `lerpPath` is a straight line between two rects (menu, lift, card, zoom); `edgeGrowPath` is UIKit's popover, growing out of a point on its edge with its length along the axis growing with its scale. `morphCurves` puts an element laid out in the path's box on the path's rect every frame with `translate` and `scale` about its top-left corner (each axis, or uniform), plus a companion opacity on the same progress or its own. `createRectMorph` presents along a path and dismisses back on a target the caller gives (a copy where the element stands, or the element itself); each interrupts the other from the rect on screen, on the path restarted there in its own law, with the presented velocity. Once a present settles nothing of the morph's stays inline. Reduced Motion is the animator's. - progress.ts: `progressCurve` (a spring's progress from 0 to 1), `mapProgress` (any curve as a function of another: a channel along a path's progress, or a companion following a driving channel, played with the driver's start to stay in lockstep), `mapRange` (the clamped linear map most companions use) and `presentedProgressVelocity` (the presented velocity projected on a new path's tangent, v·t / t·t, channels weighted to px): the unit, the curve mapping and the interruption read that the interactive-transition driver and companion motion share. Tests: every frame's rect equals the path's; each of the five presentations' models is the same rect at every progress within 0.5 px; interruption keeps the rect and the velocity; the target and inline state; Reduced Motion on a coarse and a fine pointer. Browser proofs in Chromium and WebKit: seeked frame by frame the box on screen is the path's rect within 0.5 px, a 1 s main-thread block does not stop it, and no Layout or Paint runs (Chromium trace).
1 parent 65ac34a commit da398d0

11 files changed

Lines changed: 2045 additions & 2 deletions

‎.changeset/motion-rect-morph.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[experimental] `@astryxdesign/core/motion/experimental` adds the rect morph, one way for a touch presentation to 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; `morphCurves` turns a path into compositor curves (`translate`, `scale` and a companion `opacity`); `createRectMorph` presents an element along a path and dismisses it back on a copy or on itself, each continuing the other from the rect on screen with its velocity, with Reduced Motion left to the animator. The progress helpers it runs on are exported too: `progressCurve`, `mapProgress` (one curve as a function of another, for a channel along a path or a companion following a driving channel), `mapRange` (the clamped linear map most companions use) and `presentedProgressVelocity`. Nothing is added to the package root or to any other subpath.
6+
7+
@vjeux

‎packages/core/src/motion/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ from the package entry point; components import it by path.
2626
| `projection.ts` | Release targets: the rest point nearest the projected coast; paging. |
2727
| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
2828
| `animator.ts` | Compositor animator: springs, decays and any closed-form curve compiled to Web Animations, read back analytically. |
29+
| `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. |
30+
| `rectMorph.ts` | Grow out of a source rect and shrink back into it: paths (a straight line, a popover’s edge growth), present and dismiss. |
2931
| `experimental.ts` | The experimental public subpath (`@astryxdesign/core/motion/experimental`). |
3032
| `useAnimator.ts` | React wrapper that never re-renders per frame. |
3133
| `__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. |

‎packages/core/src/motion/__tests__/motionBundle.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,7 @@
99
*/
1010

1111
export {createAnimator} from '../animator';
12+
export {progressCurve} from '../progress';
13+
export {createRectMorph, edgeGrowPath, lerpPath} from '../rectMorph';
1214
export {solveSpring, toSpring} from '../spring';
1315
export {springs} from '../uikit/springs';
Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file rectMorph.interaction.browser.spec.ts
5+
* @input The rect morph and the motion source bundled with esbuild onto a
6+
* blank fixture page; the interaction harness's busy-main-thread,
7+
* screencast and trace instruments; Chromium and WebKit on the phone
8+
* profile
9+
* @output Proof that the engine shows the morph's path: seeked frame by
10+
* frame, a present and a dismissal put the element's box on screen on the
11+
* path's rect within 0.5 px (a straight line with a fade, a popover's edge
12+
* growth); the morph keeps moving through a 1 s main-thread block; no
13+
* Layout or Paint runs while it animates (Chromium trace)
14+
* @position Browser proof for rectMorph.ts, run by `pnpm test:interaction`;
15+
* jsdom runs no animations
16+
*/
17+
18+
import {fileURLToPath} from 'node:url';
19+
import {
20+
blockMainThread,
21+
busyWindowProof,
22+
countBetween,
23+
markElement,
24+
startScreencast,
25+
traceRendering,
26+
trackMarker,
27+
} from '@astryxdesign/interaction-harness';
28+
import {expect, test, type Page} from '@playwright/test';
29+
import {build} from 'esbuild';
30+
// The page's `Motion` global (the bundle) is declared beside the animator's
31+
// proofs, in animator.interaction.browser.spec.ts.
32+
33+
let script = '';
34+
35+
test.beforeAll(async () => {
36+
const result = await build({
37+
entryPoints: [fileURLToPath(new URL('./motionBundle.ts', import.meta.url))],
38+
bundle: true,
39+
write: false,
40+
format: 'iife',
41+
globalName: 'Motion',
42+
target: 'es2022',
43+
});
44+
script = result.outputFiles[0].text;
45+
});
46+
47+
/** The surface at rest, and the 22 px square on its control it grows from. */
48+
const BOX = {x: 40, y: 204, width: 320, height: 253};
49+
const SQUARE = {x: 179, y: 160, width: 22, height: 22};
50+
/** UIKit's popover numbers (#8187): 1 % scale, 100 px of length. */
51+
const POPOVER = {origin: {x: 160, y: 0}, collapsedScale: 0.01};
52+
const SPRING = {response: 0.45, dampingRatio: 0.8};
53+
/** A slow spring for the block: well over a px per frame throughout. */
54+
const SLOW = {response: 2, dampingRatio: 1};
55+
const MARKER_INSET = 8;
56+
57+
// A real navigation (not setContent): the page keeps its own window.
58+
async function open(page: Page) {
59+
const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">
60+
<style>
61+
html, body { margin: 0; background: #fff; }
62+
.surface { position: absolute; left: ${BOX.x}px; top: ${BOX.y}px; width: ${BOX.width}px; height: ${BOX.height}px; background: #36c; }
63+
</style>
64+
<div id="surface" class="surface"></div>
65+
<script>${script}</script>`;
66+
await page.route('http://motion.test/', async route =>
67+
route.fulfill({contentType: 'text/html', body: html}),
68+
);
69+
await page.goto('http://motion.test/');
70+
}
71+
72+
type PathKind = 'line' | 'edge';
73+
74+
/**
75+
* Plays a present (or, after it, a dismissal on a copy) of `kind`, pauses
76+
* the engine, seeks it every 1/60 s, and returns the worst gap between the
77+
* box on screen and the path's rect, px, and between the opacity on screen
78+
* and the path's.
79+
*/
80+
async function seekedGap(
81+
page: Page,
82+
kind: PathKind,
83+
phase: 'present' | 'dismiss',
84+
) {
85+
return page.evaluate(
86+
async ({kind, phase, box, square, popover, spring}) => {
87+
const surface = document.getElementById('surface') as HTMLElement;
88+
const morph = Motion.createRectMorph(surface, {
89+
prefersReducedMotion: () => false,
90+
});
91+
const path =
92+
kind === 'line'
93+
? Motion.lerpPath(square, box, {opacity: [0, 1]})
94+
: Motion.edgeGrowPath({
95+
box,
96+
origin: popover.origin,
97+
axis: 'y',
98+
collapsedScale: popover.collapsedScale,
99+
collapsedLength: 100 / box.height,
100+
});
101+
let target = surface;
102+
let handle = morph.present(path, spring);
103+
if (phase === 'dismiss') {
104+
await handle.finished;
105+
target = surface.cloneNode(true) as HTMLElement;
106+
target.id = 'copy';
107+
surface.after(target);
108+
handle = morph.dismiss(path, spring, {target});
109+
}
110+
await handle.started;
111+
const animations = target.getAnimations();
112+
const progress = Motion.progressCurve(spring);
113+
for (const animation of animations) {
114+
animation.pause();
115+
}
116+
let worstRect = 0;
117+
let worstOpacity = 0;
118+
const step = 1000 / 60;
119+
for (let t = 0; t <= progress.duration * 1000 + step; t += step) {
120+
for (const animation of animations) {
121+
animation.currentTime = t;
122+
}
123+
const p = progress.at(t / 1000);
124+
// The dismissal runs the path backward, rest to source.
125+
const at = phase === 'present' ? p : 1 - p;
126+
// Past the source on an overshoot the scale crosses 0 (the copy is
127+
// transparent there): the box on screen is the flipped rect.
128+
const raw = path.rectAt(at);
129+
const expected = {
130+
x: Math.min(raw.x, raw.x + raw.width),
131+
y: Math.min(raw.y, raw.y + raw.height),
132+
width: Math.abs(raw.width),
133+
height: Math.abs(raw.height),
134+
};
135+
const rect = target.getBoundingClientRect();
136+
worstRect = Math.max(
137+
worstRect,
138+
Math.abs(rect.x - expected.x),
139+
Math.abs(rect.y - expected.y),
140+
Math.abs(rect.width - expected.width),
141+
Math.abs(rect.height - expected.height),
142+
);
143+
const opacity = Number.parseFloat(getComputedStyle(target).opacity);
144+
const expectedOpacity = Math.min(
145+
1,
146+
Math.max(0, path.opacityAt?.(at) ?? 1),
147+
);
148+
worstOpacity = Math.max(
149+
worstOpacity,
150+
Math.abs(opacity - expectedOpacity),
151+
);
152+
}
153+
return {
154+
animations: animations.length,
155+
worstRect,
156+
worstOpacity,
157+
origin: getComputedStyle(target).transformOrigin,
158+
};
159+
},
160+
{kind, phase, box: BOX, square: SQUARE, popover: POPOVER, spring: SPRING},
161+
);
162+
}
163+
164+
for (const kind of ['line', 'edge'] as const) {
165+
for (const phase of ['present', 'dismiss'] as const) {
166+
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 ({
167+
page,
168+
}) => {
169+
await open(page);
170+
const result = await seekedGap(page, kind, phase);
171+
test.info().annotations.push({
172+
type: 'seeked gap',
173+
description: JSON.stringify(result),
174+
});
175+
// translate, scale and opacity, one animation each.
176+
expect(result.animations).toBe(3);
177+
expect(result.origin).toBe('0px 0px');
178+
expect(result.worstRect).toBeLessThanOrEqual(0.5);
179+
expect(result.worstOpacity).toBeLessThanOrEqual(0.005);
180+
});
181+
}
182+
}
183+
184+
test('a present keeps growing every frame through a 1 s main-thread block', async ({
185+
page,
186+
}) => {
187+
await open(page);
188+
const surface = page.locator('#surface');
189+
await markElement(surface, {inset: MARKER_INSET});
190+
const cast = await startScreencast(page);
191+
await page.evaluate(
192+
async ({box, spring}) => {
193+
const element = document.getElementById('surface') as HTMLElement;
194+
const morph = Motion.createRectMorph(element, {
195+
prefersReducedMotion: () => false,
196+
});
197+
// From 80 % of its size, 240 px lower (on screen the whole way): the
198+
// marker in the box's corner rises the whole way, over a px a frame.
199+
const from = {
200+
x: box.x,
201+
y: box.y + 240,
202+
width: box.width * 0.8,
203+
height: box.height * 0.8,
204+
};
205+
await morph.present(Motion.lerpPath(from, box), spring).started;
206+
},
207+
{box: BOX, spring: SLOW},
208+
);
209+
const busy = await blockMainThread(page, 1000, {
210+
during: surface,
211+
minProgressMs: 40,
212+
});
213+
await page.waitForTimeout(200);
214+
const tracked = await trackMarker(page, await cast.stop());
215+
const proof = busyWindowProof(tracked, busy, {axis: 'y', settledWithin: 2});
216+
test
217+
.info()
218+
.annotations.push({type: 'busy window', description: proof.summary});
219+
expect(busy.to - busy.from).toBeGreaterThanOrEqual(1000);
220+
expect(proof.verdict.failures, proof.summary).toEqual([]);
221+
expect(proof.monotonic).toBe(true);
222+
});
223+
224+
test('no Layout or Paint runs while it animates', async ({
225+
page,
226+
browserName,
227+
}) => {
228+
test.skip(browserName !== 'chromium', 'tracing is a Chromium protocol');
229+
await open(page);
230+
let start = 0;
231+
const trace = await traceRendering(page, async () => {
232+
start = await page.evaluate(
233+
({box, square, spring}) => {
234+
const element = document.getElementById('surface') as HTMLElement;
235+
const morph = Motion.createRectMorph(element, {
236+
prefersReducedMotion: () => false,
237+
});
238+
morph.present(Motion.lerpPath(square, box, {opacity: [0, 1]}), spring);
239+
return performance.timeOrigin + performance.now();
240+
},
241+
{box: BOX, square: SQUARE, spring: SLOW},
242+
);
243+
await page.waitForTimeout(1900);
244+
});
245+
// After the frame that starts the animation.
246+
const counts = countBetween(trace, start + 50, trace.window.to);
247+
test.info().annotations.push({
248+
type: 'rendering work while animating',
249+
description: JSON.stringify(counts),
250+
});
251+
expect(counts.Layout ?? 0).toBe(0);
252+
expect(counts.Paint ?? 0).toBe(0);
253+
});

‎packages/core/src/motion/experimental.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ const NAMES = [
2727
'cubicBezier',
2828
'prefersReducedMotion',
2929
'resolveMotion',
30+
'progressCurve',
31+
'mapProgress',
32+
'mapRange',
33+
'presentedProgressVelocity',
34+
'createRectMorph',
35+
'lerpPath',
36+
'edgeGrowPath',
37+
'morphCurves',
3038
'uikit',
3139
] as const;
3240

‎packages/core/src/motion/experimental.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
/**
66
* @file experimental.ts
77
* @input The motion foundation: animator, useAnimator, spring and rubber-band
8-
* math, cubic-bézier curves, theme motion roles and the UIKit constants table
8+
* math, cubic-bézier curves, theme motion roles, the progress helpers, the
9+
* rect morph and the UIKit constants table
910
* @output The `@astryxdesign/core/motion/experimental` entry point
1011
* @position Experimental public subpath (spec:AST-017 FR21): outside the
1112
* stable compatibility promise, never re-exported from the package root or
@@ -51,6 +52,30 @@ export type {
5152
export {rubberBand, rubberBandInverse} from './rubberBand';
5253

5354
export {resolveMotion} from './resolveMotion';
55+
56+
export {
57+
mapProgress,
58+
mapRange,
59+
presentedProgressVelocity,
60+
progressCurve,
61+
} from './progress';
62+
export type {ProgressChannel} from './progress';
63+
64+
export {
65+
createRectMorph,
66+
edgeGrowPath,
67+
lerpPath,
68+
morphCurves,
69+
} from './rectMorph';
70+
export type {
71+
MorphEnd,
72+
MorphPath,
73+
MorphRect,
74+
MorphScale,
75+
RectMorph,
76+
RectMorphDismissOptions,
77+
RectMorphPlayOptions,
78+
} from './rectMorph';
5479
export {
5580
REDUCED_MOTION_FADE_QUERY,
5681
REDUCED_MOTION_INSTANT_QUERY,

0 commit comments

Comments
 (0)