An open source design system that's fully customizable and agent ready
TypeScript
fix(core): an element whose transform leaves it in place still glides (#8780)
Christopher Chedeauf0c69828b83e
diff --git a/.changeset/animated-layout-identity-transform.md b/.changeset/animated-layout-identity-transform.mdnew file mode 100644index 0000000000..15c624215a--- /dev/null+++ b/.changeset/animated-layout-identity-transform.md@@ -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.++@vjeuxdiff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.tsindex 861ae64b1b..e8f56d7ec1 100644--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts@@ -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,diff --git a/packages/core/src/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.tsindex 4428f4e93b..98f61d34e4 100644--- a/packages/core/src/motion/animatedLayout.test.ts+++ b/packages/core/src/motion/animatedLayout.test.ts@@ -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)', () => {diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 6354233b2c..1bbe067a69 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -234,10 +234,85 @@ 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;+ }+ 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);+ }+ 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 &&+ 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);@@ -245,7 +320,7 @@ function movedByApp(element: Element): boolean {style != null &&TRANSFORM_PROPERTIES.some(property => {const value = style.getPropertyValue(property);- return value !== '' && value !== 'none';+ return value !== '' && value !== 'none' && !staysInPlace(property, value);})) {return true;@@ -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])),+ ),+ );});}@@ -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.@@ -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@@ -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) {