Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/animated-layout-identity-transform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[fix] With an `animatedLayout` handle, content after a change now glides even when it keeps a transform that leaves it in place. A resting Button (`scale(1)`, computed as `matrix(1, 0, 0, 1, 0, 0)`), a pressed one (`scale(0.98)`) and a row with swipe actions at rest (`translate3d(0, 0, 0)`) used to jump to their new place as if the app were moving them, and a pressed button jumped onto the button gliding beside it. A row a swipe holds open, or anything the app translates or rotates, is still left to the app.

@vjeux
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,45 @@ test.describe('spec:AST-105 Coverage', () => {
expect(startOffset(motion.first).y).toBeCloseTo(-80, 0);
});

test("a follower with its own scale glides from its old place: its own scale is no ancestor's", async ({
page,
}) => {
await open(
page,
`<div id="area" class="area"><div id="grow" class="grow"></div>
<div id="pressed" class="row" style="transform: scale(0.98)"></div>
<div id="half" class="row" style="scale: 0.5"></div>
<div id="flipped" class="row" style="scale: -1"></div>
<div id="mirrored" class="row" style="scale: 1 -1"></div>
<div id="pressing" class="row" style="transition: transform 2s linear"></div></div>`,
);
// A press starting on #pressing: its own transition runs from
// \`transform: none\` toward a scale while the change happens.
await page.evaluate(() => {
const pressing = document.querySelector<HTMLElement>('#pressing');
if (pressing != null) {
void pressing.offsetHeight;
pressing.style.transform = 'scale(0.98)';
}
});
await change(page);
// A negative scale flips the element in place: it glides the same way.
for (const id of [
'#pressed',
'#half',
'#flipped',
'#mirrored',
'#pressing',
]) {
const motions = await page.evaluate(s => window.motionOf(s), id);
const glide = motions.find(motion => (motion.first ?? '').includes('px'));
expect(glide, `${id} ${JSON.stringify(motions)}`).toBeDefined();
// 80 px of layout, translated in its parent's space: a \`translate\`
// does not go through the element's own scale.
expect(startOffset(glide?.first ?? null).y, id).toBeCloseTo(-80, 0);
}
});

test('top-layer content is never moved', async ({page}) => {
await open(
page,
Expand Down
139 changes: 139 additions & 0 deletions packages/core/src/motion/animatedLayout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,145 @@ describe('elements the app moves itself (spec:AST-105 Coverage)', () => {
.map(p => (p.element as HTMLElement).id);
expect(moved).toEqual(['plain']);
});

it('glides a follower whose transform leaves it in place: a swipe row at rest, a resting or pressed button', async () => {
const {area, changed, phase} = setUp(
`<div id="area"><div id="changed"></div>
<div id="swipeRow" style="transform: translate3d(0px, 0px, 0px)"></div>
<div id="button" style="transform: matrix(1, 0, 0, 1, 0, 0)"></div>
<div id="pressed" style="transform: scale(0.98)"></div>
<div id="pressedMatrix" style="transform: matrix(0.98, 0, 0, 0.98, 0, 0)"></div>
<div id="scaled" style="scale: 0.98"></div>
<div id="zero" style="translate: 0px; rotate: 0deg"></div>
<div id="swiped" style="transform: translate3d(-120px, 0px, 0px)"></div>
<div id="pressedAndMoved" style="transform: matrix(0.98, 0, 0, 0.98, 0, 12)"></div></div>`,
);
const ids = [
'swipeRow',
'button',
'pressed',
'pressedMatrix',
'scaled',
'zero',
'swiped',
'pressedAndMoved',
];
for (const id of ids) {
placeAt(
document.getElementById(id) as HTMLElement,
{before: [0, 10, 400, 40], after: [0, 90, 400, 40]},
phase,
);
}
await runChange(
createAnimatedLayout(() => area),
changed,
phase,
);
const moved = played
.filter(p => p.keyframes[0].translate != null)
.map(p => (p.element as HTMLElement).id);
// A row a swipe holds open, or anything translated, is still the app's.
expect(moved.sort()).toEqual([
'button',
'pressed',
'pressedMatrix',
'scaled',
'swipeRow',
'zero',
]);
});

it('glides a follower whose own transition runs from no transform to a scale (a press starting)', async () => {
const {area, changed, phase} = setUp(
`<div id="area"><div id="changed"></div><div id="pressing"></div><div id="sliding"></div></div>`,
);
for (const id of ['pressing', 'sliding']) {
placeAt(
document.getElementById(id) as HTMLElement,
{before: [0, 10, 400, 40], after: [0, 90, 400, 40]},
phase,
);
}
class StubKeyframeEffect {
constructor(readonly frames: Keyframe[]) {}
getKeyframes() {
return this.frames;
}
}
vi.stubGlobal('KeyframeEffect', StubKeyframeEffect);
const runs = (frames: Keyframe[]) => () =>
[{effect: new StubKeyframeEffect(frames)}] as unknown as Animation[];
// A press's transition: from no transform toward a scale, in place.
(document.getElementById('pressing') as HTMLElement).getAnimations = runs([
{transform: 'none'},
{transform: 'matrix(0.98, 0, 0, 0.98, 0, 0)'},
]);
// The app sliding the element itself stays the app's.
(document.getElementById('sliding') as HTMLElement).getAnimations = runs([
{transform: 'none'},
{transform: 'translateX(120px)'},
]);
try {
await runChange(
createAnimatedLayout(() => area),
changed,
phase,
);
} finally {
vi.unstubAllGlobals();
}
const moved = played
.filter(p => p.keyframes[0].translate != null)
.map(p => (p.element as HTMLElement).id);
expect(moved).toEqual(['pressing']);
});

it('leaves a follower whose own keyframes hold an unresolved var() to the app: its value is unknown', async () => {
const {area, changed, phase} = setUp(
`<div id="area"><div id="changed"></div><div id="slide"></div><div id="slideY"></div><div id="spin"></div><div id="grow"></div></div>`,
);
for (const id of ['slide', 'slideY', 'spin', 'grow']) {
placeAt(
document.getElementById(id) as HTMLElement,
{before: [0, 10, 400, 40], after: [0, 90, 400, 40]},
phase,
);
}
class StubKeyframeEffect {
constructor(readonly frames: Keyframe[]) {}
getKeyframes() {
return this.frames;
}
}
vi.stubGlobal('KeyframeEffect', StubKeyframeEffect);
const runs = (id: string, frames: Keyframe[]) => {
(document.getElementById(id) as HTMLElement).getAnimations = () =>
[{effect: new StubKeyframeEffect(frames)}] as unknown as Animation[];
};
// An app's own slide-ins and spin, from values a custom property holds.
runs('slide', [{translate: 'var(--from)'}, {translate: '0px'}]);
runs('slideY', [
{transform: 'translateY(var(--from))'},
{transform: 'none'},
]);
runs('spin', [{transform: 'rotate(var(--angle))'}, {transform: 'none'}]);
// A scale stays in place whatever its value.
runs('grow', [{scale: 'var(--from)'}, {scale: '1'}]);
try {
await runChange(
createAnimatedLayout(() => area),
changed,
phase,
);
} finally {
vi.unstubAllGlobals();
}
const moved = played
.filter(p => p.keyframes[0].translate != null)
.map(p => (p.element as HTMLElement).id);
expect(moved).toEqual(['grow']);
});
});

describe('siblings before the change (spec:AST-105 FR3, Coverage)', () => {
Expand Down
143 changes: 134 additions & 9 deletions packages/core/src/motion/animatedLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,18 +234,93 @@ const ours = new WeakSet<Animation>();

const TRANSFORM_PROPERTIES = ['transform', 'translate', 'rotate', 'scale'];

/** The numbers in a CSS value, units dropped. */
function numbersIn(value: string): number[] {
return (value.match(/-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/gi) ?? []).map(
Number,
);
}

/**
* Whether a transform value leaves the element where it is: nothing at all
* (a swipe's `translate3d(0, 0, 0)` at rest, a button's `scale(1)`, computed
* as `matrix(1, 0, 0, 1, 0, 0)`), or a scale in place (a pressed button's
* `scale(0.98)`). A glide's `translate` composes with either; a translation,
* rotation or skew of its own is the app moving the element.
*/
function staysInPlace(property: string, value: string): boolean {
if (value === 'none') {
// No transform at all (a keyframe a press's own transition starts from).
return true;
}
if (property === 'scale') {
return true;
}
Comment on lines +256 to +258

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Admitting every scale sends self-scaled followers to the glide, where the unchanged scaleOf (line 896) divides their travel by their own scale as if an ancestor applied it. In Chromium, on an 80 px downward shift, a scale(0.5) follower starts 80 px above its old place and a pressed Button (scale(0.98)) 1.63 px above it. Taking the correction from the follower's containing box, or dividing its own scale out, keeps the glide starting at its old place.

if (value.includes('var(')) {
// An unresolved custom property in an app's own keyframes: its value is
// unknown here, so the app moves the element.
return false;
}
if (property === 'translate') {
return numbersIn(value).every(n => n === 0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A Web Animation reports its keyframes as written, so an app's translate: var(--from) keyframe reaches this branch with no digits, [].every(...) is true, and the keyframe reads as zero. Line 300 does the same for translateY(var(--from)), rotate(var(--angle)) and translate3d(var(--x, 0px), 0, 0) (only the fallback's 0 is read). In Chromium such a follower now gets the glide, whose translate masks the app's own slide: at 150 ms it sits at -35px instead of the app's +105px. Counting a value that still holds var() as the app's, for example if (value.includes('var(')) return false; after the scale branch, fixes both.

}
if (property === 'rotate') {
// An angle, after an optional axis: only the angle matters.
const numbers = numbersIn(value);
return numbers.length > 0 && numbers[numbers.length - 1] === 0;
}
// A list of transform functions, as computed (`matrix()`, `matrix3d()`)
// or as written.
const functions = [...value.matchAll(/([a-z0-9]+)\(([^)]*)\)/gi)];
return (
functions.length > 0 &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

none reaches here from an app animation's keyframes (lines 313-316) and returns false, so a follower whose own transition runs from transform: none to a scale still counts as moved; rotate: none does the same at lines 240-241. Treating none as in place for every property would match the static check at line 294.

functions.every(([, name, args]) => {
const numbers = numbersIn(args);
const fn = name.toLowerCase();
if (fn === 'matrix') {
// a b c d e f: no skew, rotation or translation.
return (
numbers.length === 6 &&
[1, 2, 4, 5].every(index => numbers[index] === 0)
);
}
if (fn === 'matrix3d') {
// Only the diagonal: a scale, nothing else.
return (
numbers.length === 16 &&
numbers.every((n, index) => index % 5 === 0 || n === 0)
);
}
if (fn === 'rotate3d') {
return numbers[3] === 0;
}
if (fn.startsWith('scale')) {
return true;
}
if (
fn.startsWith('translate') ||
fn.startsWith('rotate') ||
fn.startsWith('skew')
) {
return numbers.every(n => n === 0);
}
return false;
})
);
}

/**
* Whether the app moves `element` itself: its own `transform`, `translate`,
* `rotate` or `scale`, or a running animation of one this module did not
* start.
* Whether the app moves `element` itself: its own `transform`, `translate`
* or `rotate`, or a running animation of one this module did not start. A
* value that leaves it in place (nothing, or a scale) is not a move.
*/
function movedByApp(element: Element): boolean {
const style = element.ownerDocument.defaultView?.getComputedStyle(element);
if (
style != null &&
TRANSFORM_PROPERTIES.some(property => {
const value = style.getPropertyValue(property);
return value !== '' && value !== 'none';
return value !== '' && value !== 'none' && !staysInPlace(property, value);
})
) {
return true;
Expand All @@ -263,7 +338,13 @@ function movedByApp(element: Element): boolean {
}
return effect
.getKeyframes()
.some(frame => TRANSFORM_PROPERTIES.some(property => property in frame));
.some(frame =>
TRANSFORM_PROPERTIES.some(
property =>
property in frame &&
!staysInPlace(property, String(frame[property])),
),
);
});
}

Expand Down Expand Up @@ -702,13 +783,19 @@ function visibleRect(area: Element): DOMRect {
}

/** The element's rendered scale against its layout size (a scaled ancestor). */
function scaleOf(element: Element, rect: DOMRect): {x: number; y: number} {
function scaleOf(
element: Element,
rect: DOMRect,
own: {readonly x: number; readonly y: number} = {x: 1, y: 1},
): {x: number; y: number} {
const html = element as HTMLElement;
const x =
html.offsetWidth > 0 && rect.width > 0 ? rect.width / html.offsetWidth : 1;
html.offsetWidth > 0 && rect.width > 0
? rect.width / html.offsetWidth / own.x
: 1;
const y =
html.offsetHeight > 0 && rect.height > 0
? rect.height / html.offsetHeight
? rect.height / html.offsetHeight / own.y
: 1;
// Subpixel rounding makes an unscaled element read a hair off 1; only a
// real scale is corrected.
Expand All @@ -718,6 +805,42 @@ function scaleOf(element: Element, rect: DOMRect): {x: number; y: number} {
};
}

/**
* The scale an element's own `scale` and `transform` give it, on each axis
* (a follower that keeps one in place, `staysInPlace`). A glide's `translate`
* does not go through them: the individual transform properties apply
* `translate` first, in the parent's space.
*/
function ownScaleOf(element: Element): {x: number; y: number} {
const style = element.ownerDocument.defaultView?.getComputedStyle(element);
if (style == null) {
return {x: 1, y: 1};
}
let x = 1;
let y = 1;
const scale = style.getPropertyValue('scale');
if (scale !== '' && scale !== 'none') {
const [sx = 1, sy = sx] = numbersIn(scale);
// Its size, not its direction: a negative scale flips the element in
// place, and its measured box stays positive.
x *= Math.abs(sx);
y *= Math.abs(sy);
}
// The computed transform is a matrix: its first column's length is the
// scale on x, its second's on y.
const matrix = /^matrix(3d)?\(([^)]*)\)/.exec(
style.getPropertyValue('transform'),
);
if (matrix != null) {
const m = numbersIn(matrix[2]);
const [a = 1, b = 0, c = 0, d = 1] =
matrix[1] == null ? m : [m[0], m[1], m[4], m[5]];
x *= Math.hypot(a, b);
y *= Math.hypot(c, d);
}
return {x: x || 1, y: y || 1};
}

function flush(batch: Batch): void {
batches.delete(batch.area);
// What each change's walk measured before it: an element added by the
Expand Down Expand Up @@ -819,7 +942,9 @@ function flush(batch: Batch): void {
const after = entry.after as DOMRect;
if (intersects(entry.before, visible) || intersects(after, visible)) {
entry.isMovedByApp = movedByApp(entry.element);
entry.scale = scaleOf(entry.element, after);
// Only its ancestors' scale is corrected: its own scale or transform
// (a press's scale) does not apply to the glide's `translate`.
entry.scale = scaleOf(entry.element, after, ownScaleOf(entry.element));
}
}
for (const entry of entries) {
Expand Down
Loading