An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a layout motion's copy carries on the CSS animations and transitions running in it (#9534)
Christopher Chedeau8ddcfe11c893
diff --git a/.changeset/copy-carries-css-motion.md b/.changeset/copy-carries-css-motion.mdnew file mode 100644index 0000000000..09661362f0--- /dev/null+++ b/.changeset/copy-carries-css-motion.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] The transient copy a layout motion holds of old content (an in-place swap's old content, the SideNav rail's and AppShell content's old state during a collapse or expand) carries on the CSS animations and transitions running in it from where they were. It no longer starts each CSS animation again (a press highlight lit again, an entrance that had played playing again, whatever its fill) or shows a transition's end at once.++@vjeuxdiff --git a/packages/core/src/Layer/__tests__/preserveAnimations.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/preserveAnimations.interaction.browser.spec.tsnew file mode 100644index 0000000000..03d3dc786b--- /dev/null+++ b/packages/core/src/Layer/__tests__/preserveAnimations.interaction.browser.spec.ts@@ -0,0 +1,85 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file preserveAnimations.interaction.browser.spec.ts+ * @input `preserveAnimations` bundled with esbuild onto a fixture page, in+ * real Chromium and WebKit+ * @output A layer placed afresh keeps its content's CSS motion: an ended+ * `@starting-style` fade-in stays ended, and a running animation goes on+ * from where it was+ * @position Real-browser verification of the layer runtime's re-placement+ */++import {fileURLToPath} from 'node:url';+import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {build} from 'esbuild';+import type * as Bundle from '../preserveAnimations';++declare global {+ interface Window {+ LayerReplacement: typeof Bundle;+ }+}++let script = '';++test.beforeAll(async () => {+ const result = await build({+ entryPoints: [+ fileURLToPath(new URL('../preserveAnimations.ts', import.meta.url)),+ ],+ bundle: true,+ write: false,+ format: 'iife',+ globalName: 'LayerReplacement',+ target: 'es2022',+ });+ script = result.outputFiles[0].text;+});++test('a layer placed afresh does not play an ended @starting-style fade-in again, and a running animation goes on from where it was', async ({+ page,+}) => {+ const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">+<style>+ .segment { display: block; transition: opacity 1000ms linear; }+ @starting-style { .segment { opacity: 0; } }+ @keyframes layer-pulse { from { opacity: 1; } to { opacity: 0.2; } }+ .pulse { display: block; animation: layer-pulse 1000ms linear infinite; }+</style>+<div id="layer"><span class="segment">Streamed text</span><span class="pulse">Typing</span></div>+<script>${script}</script>`;+ await page.route('http://layer.test/', async route =>+ route.fulfill({contentType: 'text/html', body: html}),+ );+ await page.goto('http://layer.test/');+ const result = await page.evaluate(async () => {+ const layer = document.querySelector('#layer') as HTMLElement;+ const segment = layer.querySelector('.segment') as HTMLElement;+ const pulse = layer.querySelector('.pulse') as HTMLElement;+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ // The segment's fade-in has ended, and the pulse is 400 ms in.+ for (const animation of segment.getAnimations()) {+ animation.finish();+ }+ const [running] = pulse.getAnimations();+ running.currentTime = 400;+ // As the runtime places a layer afresh: out of rendering for one forced+ // layout, and back. Coming back starts the fade-in again.+ window.LayerReplacement.preserveAnimations(layer, () => {+ layer.style.display = 'none';+ layer.getBoundingClientRect();+ layer.style.display = '';+ });+ const [pulseAfter] = pulse.getAnimations();+ return {+ segment: Number(getComputedStyle(segment).opacity),+ pulse: pulseAfter == null ? null : Number(pulseAfter.currentTime),+ };+ });+ expect(result.segment).toBe(1);+ expect(result.pulse).not.toBeNull();+ expect(Math.abs(Number(result.pulse) - 400)).toBeLessThan(1);+});diff --git a/packages/core/src/Layer/preserveAnimations.ts b/packages/core/src/Layer/preserveAnimations.tsindex eb4eb9825b..2707d8f0b9 100644--- a/packages/core/src/Layer/preserveAnimations.ts+++ b/packages/core/src/Layer/preserveAnimations.ts@@ -11,245 +11,23 @@** Taking an element out of rendering cancels every CSS animation and* transition of it and its subtree. When it returns, the browser creates the- * animations again from the stylesheet, at their start, and the transitions- * not at all; script-created animations are untouched. `preserveAnimations`- * reads every animation's state first and, afterwards, gives each recreated- * CSS animation that state and resumes each cancelled transition with a- * script animation at the same point.- *- * The state is read generically, from what the platform exposes: every- * accessor with a setter on the animation's and its effect's prototype- * chains, every field of the effect's timing, and its keyframes. Only values- * that differ from the recreated animation's are written, so a value the- * stylesheet controls stays under its control. A few members are not plain- * state and are handled in their own step (`ORDERED`); the rest need no- * handling (`DERIVED`). What cannot be carried over is the Animation and- * effect objects themselves: the old ones are idle, their `addEventListener`- * listeners and `finished`/`ready` promises stay with them, and the browser- * fires `animationcancel`/`transitioncancel` for them and `animationstart`+ * animations again from the stylesheet, at their start. It starts no+ * transition but one from `@starting-style`, and script-created animations+ * are untouched. `preserveAnimations` reads every animation's state first.+ * Afterwards it gives each recreated CSS animation that state, and resumes+ * each cancelled transition with a script animation at the same point. Any+ * other animation the return started is finished, unless it never ends+ * (motion/carryAnimations.ts). The browser fires+ * `animationcancel`/`transitioncancel` for the old ones and `animationstart`* for the new ones.*/-/**- * Animation members written in a fixed order rather than generically: the- * timeline before the range that is measured on it, the rate before the- * time, and the start time (or, for a paused animation, the current time)- * last, once the play state is set. `effect` is not- * replaced, because a CSS animation whose effect script replaces leaves the- * stylesheet's control; its state is copied onto the new effect instead.- */-const ORDERED = new Set([- 'effect',- 'timeline',- 'rangeStart',- 'rangeEnd',- 'playbackRate',- 'startTime',- 'currentTime',-]);--type Writable = Record<string, unknown>;--/** Every accessor with a setter on `object`'s prototype chain. */-function writableAccessors(object: object): string[] {- const names = new Set<string>();- for (- let proto: object | null = Object.getPrototypeOf(object);- proto != null && proto !== Object.prototype;- proto = Object.getPrototypeOf(proto)- ) {- for (const [name, descriptor] of Object.entries(- Object.getOwnPropertyDescriptors(proto),- )) {- if (descriptor.set != null) {- names.add(name);- }- }- }- return [...names];-}--/**- * A textual form of a value that is compared by content rather than by- * identity: a CSS numeric value (as in a timeline range offset) through its- * serialization, a plain object (a range) through its members. Anything else- * is compared by identity (`null`).- */-function contentOf(value: unknown): string | null {- if (- typeof CSSNumericValue !== 'undefined' &&- value instanceof CSSNumericValue- ) {- return value.toString();- }- if (- value != null &&- typeof value === 'object' &&- Object.getPrototypeOf(value) === Object.prototype- ) {- return Object.entries(value)- .map(([key, inner]) => `${key}:${contentOf(inner) ?? String(inner)}`)- .join(';');- }- return null;-}--function differs(a: unknown, b: unknown): boolean {- if (a === b) {- return false;- }- const textA = contentOf(a);- return textA == null || textA !== contentOf(b);-}--interface Saved {- animation: Animation;- name: string;- target: Element | null;- pseudoElement: string | null;- values: Writable;- effectValues: Writable;- timing: EffectTiming | null;- keyframes: ComputedKeyframe[] | null;- playState: AnimationPlayState;- replaceState: AnimationReplaceState;-}--function save(animation: Animation): Saved {- const effect = animation.effect as KeyframeEffect | null;- const values: Writable = {};- for (const name of writableAccessors(animation)) {- values[name] = (animation as unknown as Writable)[name];- }- const effectValues: Writable = {};- if (effect != null) {- for (const name of writableAccessors(effect)) {- effectValues[name] = (effect as unknown as Writable)[name];- }- }- return {- animation,- name:- (animation as Animation & {animationName?: string}).animationName ?? '',- target: effect?.target ?? null,- pseudoElement: effect?.pseudoElement ?? null,- values,- effectValues,- timing: effect?.getTiming() ?? null,- keyframes: effect?.getKeyframes() ?? null,- playState: animation.playState,- replaceState: animation.replaceState,- };-}--function write(object: object, name: string, value: unknown): void {- (object as Writable)[name] = value;-}--/** Give `next` the effect state `saved` had: every writable member. */-function restoreEffect(next: KeyframeEffect, saved: Saved): void {- for (const name of writableAccessors(next)) {- if (- name in saved.effectValues &&- differs(saved.effectValues[name], (next as unknown as Writable)[name])- ) {- write(next, name, saved.effectValues[name]);- }- }- if (saved.timing != null) {- const timing = next.getTiming() as unknown as Writable;- const changed: Writable = {};- for (const [field, value] of Object.entries(saved.timing)) {- if (differs(value, timing[field])) {- changed[field] = value;- }- }- if (Object.keys(changed).length > 0) {- next.updateTiming(changed);- }- }- if (- saved.keyframes != null &&- JSON.stringify(saved.keyframes) !== JSON.stringify(next.getKeyframes())- ) {- next.setKeyframes(saved.keyframes);- }-}--/** Give `next` the state `saved` had, member by member. */-function restore(next: Animation, saved: Saved): void {- const effect = next.effect as KeyframeEffect | null;- if (effect != null) {- restoreEffect(effect, saved);- }- const current = next as unknown as Writable;- for (const name of ['timeline', 'rangeStart', 'rangeEnd']) {- if (name in saved.values && differs(saved.values[name], current[name])) {- write(next, name, saved.values[name]);- }- }- for (const name of writableAccessors(next)) {- if (- !ORDERED.has(name) &&- name in saved.values &&- differs(saved.values[name], current[name])- ) {- write(next, name, saved.values[name]);- }- }- if (saved.replaceState === 'persisted' && next.replaceState !== 'persisted') {- next.persist();- }- const rate = saved.values.playbackRate;- if (typeof rate === 'number' && rate !== next.playbackRate) {- next.playbackRate = rate;- }- if (saved.playState === 'paused' && next.playState !== 'paused') {- next.pause();- } else if (saved.playState !== 'paused' && next.playState === 'paused') {- next.play();- }- // A running animation is anchored to its timeline by its start time, which- // carries its current time on exactly. A paused one has none and keeps its- // current time. A finished one holds its end: finishing it again holds the- // same time, though its start time is then counted from now, since script- // cannot set a start time and a held time together.- const start = saved.values.startTime as CSSNumberish | null | undefined;- const time = saved.values.currentTime as CSSNumberish | null | undefined;- if (saved.playState === 'finished') {- next.finish();- } else if (start != null) {- next.startTime = start;- } else if (time != null) {- next.currentTime = time;- }-}--/** Resume a cancelled CSS transition with a script animation in its state. */-function resumeTransition(saved: Saved): void {- if (saved.target == null || saved.keyframes == null) {- return;- }- const replacement = saved.target.animate(saved.keyframes, {- pseudoElement: saved.pseudoElement ?? undefined,- });- restore(replacement, saved);-}--function isTransition(animation: Animation): boolean {- return (- typeof CSSTransition !== 'undefined' && animation instanceof CSSTransition- );-}+import {restoreAnimations, saveAnimation} from '../motion/carryAnimations';/*** Run `reset`, which takes `root` out of rendering and back, and put every* CSS animation and transition of `root` and its subtree back in the state it- * was in before. Recreated animations are matched to the ones they replace by- * element, pseudo-element and name, in order, and then by name alone (an- * effect script moved to another element or pseudo-element); a recreated- * animation with no predecessor (an entry animation that had already played- * and been dropped) is finished.+ * was in before.*/export function preserveAnimations(root: Element, reset: () => void): void {if (typeof root.getAnimations !== 'function') {@@ -257,48 +35,7 @@ export function preserveAnimations(root: Element, reset: () => void): void {return;}const before = root.getAnimations({subtree: true});- const saved = before.map(save);+ const saved = before.map(saveAnimation);reset();- const after = root.getAnimations({subtree: true});- const current = new Set(after);- const survivors = new Set(before);- const cancelled: Saved[] = [];- for (const state of saved) {- if (current.has(state.animation)) {- continue;- }- if (isTransition(state.animation)) {- resumeTransition(state);- } else {- cancelled.push(state);- }- }- const recreated = after.filter(animation => !survivors.has(animation));- const unmatched: Animation[] = [];- for (const animation of recreated) {- const effect = animation.effect as KeyframeEffect | null;- const name =- (animation as Animation & {animationName?: string}).animationName ?? '';- const index = cancelled.findIndex(- state =>- state.name === name &&- state.target === (effect?.target ?? null) &&- state.pseudoElement === (effect?.pseudoElement ?? null),- );- if (index === -1) {- unmatched.push(animation);- } else {- restore(animation, cancelled.splice(index, 1)[0]);- }- }- for (const animation of unmatched) {- const name =- (animation as Animation & {animationName?: string}).animationName ?? '';- const index = cancelled.findIndex(state => state.name === name);- if (index === -1) {- animation.finish();- } else {- restore(animation, cancelled.splice(index, 1)[0]);- }- }+ restoreAnimations(root, saved, new Set(before));}diff --git a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.tsindex 99bdef377e..48c81fb742 100644--- a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts+++ b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts@@ -399,9 +399,23 @@ interface MotionPart {readonly holdsPage: boolean;}+/**+ * One press feedback animation `recordMotion` keeps apart: the toggle's own,+ * or on a copy of it the old state holds (`onCopy`). `name` is a CSS+ * animation's; `startTime` is read while it runs, since a cancelled animation+ * drops it.+ */+interface PressPart {+ readonly onCopy: boolean;+ readonly name: string | null;+ startTime: number | null;+}+/** The record `recordMotion` keeps on the page, for `settledMotion`. */interface MotionRecord {readonly seen: Map<Animation, MotionPart>;+ /** Press feedback, apart from the motion. */+ readonly press: Map<Animation, PressPart>;readonly collect: () => void;sampling: boolean;}@@ -409,21 +423,43 @@ interface MotionRecord {/*** Starts recording the motion a press of the toggle causes: every animation* running on any frame from now on, described when first seen. Animations on- * the toggle element itself are its press feedback (its highlight's release- * fade runs on the button), not the rail's, so they are left out; everything- * inside it, its chevron included, stays in. `settledMotion` ends the record.+ * the toggle element itself are its press feedback, not the rail's: its+ * highlight's release fade runs on the button. So are those on any element+ * the press model marks (`data-astryx-press`), such as the toggle in the copy+ * the old state holds. That copy shows the press as the toggle did. They are+ * kept apart, as press feedback. Everything inside the toggle, its chevron+ * included, stays in. `settledMotion` ends the record.*/async function recordMotion(page: Page): Promise<void> {await toggleButton(page).evaluate(toggle => {const seen = new Map<Animation, MotionPart>();+ const press = new Map<Animation, PressPart>();const collect = () => {for (const animation of document.getAnimations()) {const effect = animation.effect;+ const known = press.get(animation);+ if (known != null) {+ if (animation.startTime != null) {+ known.startTime = Number(animation.startTime);+ }+ continue;+ }+ if (seen.has(animation) || !(effect instanceof KeyframeEffect)) {+ continue;+ }if (- seen.has(animation) ||- !(effect instanceof KeyframeEffect) ||- effect.target === toggle+ effect.target === toggle ||+ effect.target?.hasAttribute('data-astryx-press') === true) {+ press.set(animation, {+ onCopy: effect.target !== toggle,+ name:+ animation instanceof CSSAnimation+ ? animation.animationName+ : null,+ startTime:+ animation.startTime == null ? null : Number(animation.startTime),+ });continue;}const properties = new Set<string>();@@ -445,7 +481,7 @@ async function recordMotion(page: Page): Promise<void> {});}};- const record: MotionRecord = {seen, collect, sampling: true};+ const record: MotionRecord = {seen, press, collect, sampling: true};(window as unknown as {railMotion: MotionRecord}).railMotion = record;const sample = () => {if (record.sampling) {@@ -501,6 +537,26 @@ async function settledMotion(page: Page): Promise<ReadonlyArray<MotionPart>> {});}+/**+ * The press feedback the record kept apart from the motion, once it has+ * settled. For each: where it ran (the toggle, or a copy of it), a CSS+ * animation's name, and its start time as read while it ran.+ */+async function pressFeedback(+ page: Page,+): Promise<+ ReadonlyArray<{onCopy: boolean; name: string | null; startTime: number}>+> {+ return page.evaluate(() => {+ const record = (window as unknown as {railMotion: MotionRecord}).railMotion;+ return [...record.press.values()].map(({onCopy, name, startTime}) => ({+ onCopy,+ name,+ startTime: startTime ?? Number.NaN,+ }));+ });+}+test.describe('component:SideNav FR6 and component:AppShell FR17 under a finger', () => {test('a tap collapses and expands the rail with its edge on the content on every frame, no width animation, and a hidden copy gone at rest', async ({page,@@ -628,6 +684,59 @@ test.describe('component:SideNav FR6 and component:AppShell FR17 under a finger'});});}++ test(`under Reduce Motion a press held past its onset still only cross-fades, and the old state's copy shows the toggle's press fading in step with the toggle (design:reduced-motion DR2)`, async ({+ page,+ }) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ await openStory(page, PHONE_STORY);+ await recordMotion(page);+ // Held until the press shows, its release fades the press at once, before+ // the tap's click collapses the rail. So the copy of the old state holds a+ // toggle whose press is fading.+ const box = await toggleButton(page).boundingBox();+ if (box == null) {+ throw new Error('the toggle has no box');+ }+ const point = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [point],+ });+ await expect(toggleButton(page)).toHaveAttribute('data-astryx-press', 'on');+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await expect(toggleButton(page)).toHaveAccessibleName('Expand sidebar');+ const motion = await settledMotion(page);+ expect(motion.length).toBeGreaterThan(0);+ for (const {properties, endTime, holdsPage} of motion) {+ expect(properties).toEqual(['opacity']);+ expect(endTime).toBeLessThanOrEqual(200);+ expect(holdsPage).toBe(false);+ }+ // The copy's press fade runs on the toggle's own start, from where the+ // toggle's had got to, not again from its start.+ const press = await pressFeedback(page);+ const onCopy = press.filter(fade => fade.onCopy && fade.name != null);+ expect(onCopy.length).toBeGreaterThan(0);+ for (const fade of onCopy) {+ const own = press.find(+ other => !other.onCopy && other.name === fade.name,+ );+ expect(own, JSON.stringify(press)).toBeDefined();+ expect(+ Math.abs(fade.startTime - (own?.startTime ?? Number.NaN)),+ JSON.stringify(press),+ ).toBeLessThan(1);+ }+ expect(await railAtRest(page)).toMatchObject({+ labelsShown: false,+ copies: 0,+ });+ });});test.describe('component:SideNav FR6 and component:AppShell FR17 under a mouse', () => {diff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.tsindex edcd44a4e2..43a1f06930 100644--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts@@ -2861,6 +2861,108 @@ test.describe('spec:AST-105 FR9 (the edge reveal)', () => {reportSkew(moving, browserName);});+ test('a copy carries on the CSS animations and transitions running in the old state, from where they were', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="row" style="display: flex; height: 300px">+ <nav id="panel" style="width: 260px; flex: none; background: #ccf">+ <span class="pulse">Projects</span>+ <span class="fade">Inbox</span>+ <span class="entered">Done</span>+ <span class="entered-backwards">Later</span>+ <span class="entered-unfilled">Archive</span>+ <span class="arrived">Sent</span>+ </nav>+ <div id="column" style="flex: 1; background: #efe">The page</div>+ </div></div>`,+ `#panel.narrow { width: 48px !important; }+ @keyframes copy-pulse { from { opacity: 1; } to { opacity: 0.2; } }+ .pulse { animation: copy-pulse 1000ms linear infinite; }+ .fade { display: inline-block; transition: opacity 1000ms linear; }+ .fade.out { opacity: 0; }+ @keyframes copy-enter { from { translate: 0 20px; } to { translate: 0 0; } }+ .entered { display: inline-block; animation: copy-enter 100ms linear both; }+ .entered-backwards { display: inline-block; animation: copy-enter 100ms linear backwards; }+ .entered-unfilled { display: inline-block; animation: copy-enter 100ms linear; }+ .arrived { display: inline-block; transition: opacity 1000ms linear; }+ @starting-style { .arrived { opacity: 0; } }`,+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area');+ const row = document.querySelector('#row') as HTMLElement;+ const panel = document.querySelector('#panel') as HTMLElement;+ const column = document.querySelector('#column') as HTMLElement;+ const AL = window.AnimatedLayout;+ const layout = AL.createAnimatedLayout(() => area);+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ const pick = (root: ParentNode, name: string) =>+ root.querySelector(`.${name}`) as HTMLElement;+ // The old state runs a looping animation 400 ms in, and a transition+ // 400 ms into its second. Three entrances have played. One holds its+ // end, and two (backwards-filled and unfilled) have left the element.+ const [pulse] = pick(panel, 'pulse').getAnimations();+ pulse.currentTime = 400;+ pick(panel, 'fade').classList.add('out');+ const [fade] = pick(panel, 'fade').getAnimations();+ fade.currentTime = 400;+ for (const name of ['entered', 'entered-backwards', 'entered-unfilled']) {+ pick(panel, name).getAnimations()[0].finish();+ }+ // A `@starting-style` fade-in has ended too, and a clone starts it again.+ for (const animation of pick(panel, 'arrived').getAnimations()) {+ animation.finish();+ }+ // Collapse: the old, wide panel is held as a copy.+ const hold = AL.holdLayoutEdge(layout, panel, {edge: 'inline-end'});+ const report = AL.reportLayoutChange(layout, () => panel);+ report.measureBefore();+ panel.classList.add('narrow');+ report.animate();+ if (hold == null) {+ throw new Error('the collapse held nothing');+ }+ AL.playLayoutEdge(hold, panel, layout, {+ edge: 'inline-end',+ rideWith: column,+ });+ const copy = row.querySelector<HTMLElement>(+ ':scope > [inert][aria-hidden="true"]',+ );+ if (copy == null) {+ throw new Error('the collapse held no copy');+ }+ const [copiedPulse] = pick(copy, 'pulse').getAnimations();+ return {+ pulse: pulse.currentTime,+ copiedPulse: copiedPulse?.currentTime ?? null,+ fade: Number(getComputedStyle(pick(panel, 'fade')).opacity),+ copiedFade: Number(getComputedStyle(pick(copy, 'fade')).opacity),+ entered: ['entered', 'entered-backwards', 'entered-unfilled'].map(+ name => getComputedStyle(pick(panel, name)).translate,+ ),+ copiedEntered: ['entered', 'entered-backwards', 'entered-unfilled'].map(+ name => getComputedStyle(pick(copy, name)).translate,+ ),+ arrived: Number(getComputedStyle(pick(panel, 'arrived')).opacity),+ copiedArrived: Number(getComputedStyle(pick(copy, 'arrived')).opacity),+ };+ });+ // Each runs on in the copy from where it was. A clone would start a CSS+ // animation again and show a transition's end. No entrance plays again,+ // whether it holds its end or not, a `@starting-style` fade-in included.+ expect(result.copiedPulse).not.toBeNull();+ expect(Math.abs(Number(result.copiedPulse) - result.pulse)).toBeLessThan(1);+ expect(result.fade).toBeGreaterThan(0.1);+ expect(Math.abs(result.copiedFade - result.fade)).toBeLessThan(0.01);+ expect(result.copiedEntered).toEqual(result.entered);+ expect(result.arrived).toBe(1);+ expect(result.copiedArrived).toBe(1);+ });+for (const [side, direction, collapsed] of [['start', 'ltr', 48],['start', 'rtl', 0],diff --git a/packages/core/src/motion/carryAnimations.ts b/packages/core/src/motion/carryAnimations.tsnew file mode 100644index 0000000000..e743c0c3f3--- /dev/null+++ b/packages/core/src/motion/carryAnimations.ts@@ -0,0 +1,389 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file carryAnimations.ts+ * @input The CSS animations and transitions of an element and its subtree,+ * read before the browser starts them afresh+ * @output Exports `saveAnimations` and `carryAnimations`, which carry them on+ * in a clone of the element. Also `saveAnimation` and `restoreAnimations`,+ * which put them back after a display reset+ * @position Motion foundation; the transient copy (transientCopy.ts) and the+ * layer runtime's re-placement (Layer/preserveAnimations.ts) use it+ */++/**+ * Animation members written in a fixed order rather than generically: the+ * timeline before the range that is measured on it, the rate before the+ * time, and the start time (or, for a paused animation, the current time)+ * last, once the play state is set. `effect` is not+ * replaced, because a CSS animation whose effect script replaces leaves the+ * stylesheet's control; its state is copied onto the new effect instead.+ */+const ORDERED = new Set([+ 'effect',+ 'timeline',+ 'rangeStart',+ 'rangeEnd',+ 'playbackRate',+ 'startTime',+ 'currentTime',+]);++type Writable = Record<string, unknown>;++/** Every accessor with a setter on `object`'s prototype chain. */+function writableAccessors(object: object): string[] {+ const names = new Set<string>();+ for (+ let proto: object | null = Object.getPrototypeOf(object);+ proto != null && proto !== Object.prototype;+ proto = Object.getPrototypeOf(proto)+ ) {+ for (const [name, descriptor] of Object.entries(+ Object.getOwnPropertyDescriptors(proto),+ )) {+ if (descriptor.set != null) {+ names.add(name);+ }+ }+ }+ return [...names];+}++/**+ * A textual form of a value that is compared by content rather than by+ * identity: a CSS numeric value (as in a timeline range offset) through its+ * serialization, a plain object (a range) through its members. Anything else+ * is compared by identity (`null`).+ */+function contentOf(value: unknown): string | null {+ if (+ typeof CSSNumericValue !== 'undefined' &&+ value instanceof CSSNumericValue+ ) {+ return value.toString();+ }+ if (+ value != null &&+ typeof value === 'object' &&+ Object.getPrototypeOf(value) === Object.prototype+ ) {+ return Object.entries(value)+ .map(([key, inner]) => `${key}:${contentOf(inner) ?? String(inner)}`)+ .join(';');+ }+ return null;+}++function differs(a: unknown, b: unknown): boolean {+ if (a === b) {+ return false;+ }+ const textA = contentOf(a);+ return textA == null || textA !== contentOf(b);+}++/** One animation's state, read before the browser starts it afresh. */+export interface SavedAnimation {+ animation: Animation;+ name: string;+ target: Element | null;+ pseudoElement: string | null;+ values: Writable;+ effectValues: Writable;+ timing: EffectTiming | null;+ keyframes: ComputedKeyframe[] | null;+ playState: AnimationPlayState;+ replaceState: AnimationReplaceState;+}++/**+ * Reads one animation's state generically, from what the platform exposes.+ * That is every accessor with a setter on the animation's and its effect's+ * prototype chains, every field of the effect's timing, and its keyframes. Only values+ * that differ from the recreated animation's are written back, so a value the+ * stylesheet controls stays under its control. A few members are not plain+ * state and are written in their own step (`ORDERED`). The Animation and+ * effect objects themselves cannot be carried over: the old ones keep their+ * listeners and promises.+ */+export function saveAnimation(animation: Animation): SavedAnimation {+ const effect = animation.effect as KeyframeEffect | null;+ const values: Writable = {};+ for (const name of writableAccessors(animation)) {+ values[name] = (animation as unknown as Writable)[name];+ }+ const effectValues: Writable = {};+ if (effect != null) {+ for (const name of writableAccessors(effect)) {+ effectValues[name] = (effect as unknown as Writable)[name];+ }+ }+ return {+ animation,+ name:+ (animation as Animation & {animationName?: string}).animationName ?? '',+ target: effect?.target ?? null,+ pseudoElement: effect?.pseudoElement ?? null,+ values,+ effectValues,+ timing: effect?.getTiming() ?? null,+ keyframes: effect?.getKeyframes() ?? null,+ playState: animation.playState,+ replaceState: animation.replaceState,+ };+}++function write(object: object, name: string, value: unknown): void {+ (object as Writable)[name] = value;+}++/** Give `next` the effect state `saved` had: every writable member. */+function restoreEffect(next: KeyframeEffect, saved: SavedAnimation): void {+ for (const name of writableAccessors(next)) {+ if (+ name in saved.effectValues &&+ differs(saved.effectValues[name], (next as unknown as Writable)[name])+ ) {+ write(next, name, saved.effectValues[name]);+ }+ }+ if (saved.timing != null) {+ const timing = next.getTiming() as unknown as Writable;+ const changed: Writable = {};+ for (const [field, value] of Object.entries(saved.timing)) {+ if (differs(value, timing[field])) {+ changed[field] = value;+ }+ }+ if (Object.keys(changed).length > 0) {+ next.updateTiming(changed);+ }+ }+ if (+ saved.keyframes != null &&+ JSON.stringify(saved.keyframes) !== JSON.stringify(next.getKeyframes())+ ) {+ next.setKeyframes(saved.keyframes);+ }+}++/** Give `next` the state `saved` had, member by member. */+function restore(next: Animation, saved: SavedAnimation): void {+ const effect = next.effect as KeyframeEffect | null;+ if (effect != null) {+ restoreEffect(effect, saved);+ }+ const current = next as unknown as Writable;+ for (const name of ['timeline', 'rangeStart', 'rangeEnd']) {+ if (name in saved.values && differs(saved.values[name], current[name])) {+ write(next, name, saved.values[name]);+ }+ }+ for (const name of writableAccessors(next)) {+ if (+ !ORDERED.has(name) &&+ name in saved.values &&+ differs(saved.values[name], current[name])+ ) {+ write(next, name, saved.values[name]);+ }+ }+ if (saved.replaceState === 'persisted' && next.replaceState !== 'persisted') {+ next.persist();+ }+ const rate = saved.values.playbackRate;+ if (typeof rate === 'number' && rate !== next.playbackRate) {+ next.playbackRate = rate;+ }+ if (saved.playState === 'paused' && next.playState !== 'paused') {+ next.pause();+ } else if (saved.playState !== 'paused' && next.playState === 'paused') {+ next.play();+ }+ // A running animation is anchored to its timeline by its start time, which+ // carries its current time on exactly. A paused one has none and keeps its+ // current time. A finished one holds its end: finishing it again holds the+ // same time, though its start time is then counted from now, since script+ // cannot set a start time and a held time together.+ const start = saved.values.startTime as CSSNumberish | null | undefined;+ const time = saved.values.currentTime as CSSNumberish | null | undefined;+ if (saved.playState === 'finished') {+ next.finish();+ } else if (start != null) {+ next.startTime = start;+ } else if (time != null) {+ next.currentTime = time;+ }+}++/** Resume a cancelled CSS transition with a script animation in its state. */+function resumeTransition(saved: SavedAnimation): void {+ if (saved.target == null || saved.keyframes == null) {+ return;+ }+ const replacement = saved.target.animate(saved.keyframes, {+ pseudoElement: saved.pseudoElement ?? undefined,+ });+ restore(replacement, saved);+}++function isTransition(animation: Animation): boolean {+ return (+ typeof CSSTransition !== 'undefined' && animation instanceof CSSTransition+ );+}++function isCssAnimation(animation: Animation): animation is CSSAnimation {+ return (+ typeof CSSAnimation !== 'undefined' && animation instanceof CSSAnimation+ );+}++/**+ * Finishes an animation that ends: an infinite one cannot be finished, and is+ * left as it runs.+ */+function finishIfItEnds(animation: Animation): void {+ const end = animation.effect?.getComputedTiming().endTime;+ if (+ end != null &&+ Number.isFinite(Number(end)) &&+ animation.playbackRate !== 0+ ) {+ animation.finish();+ }+}++/** The members a copy's animation does not take: its element's keep them. */+const IDENTITY_MEMBERS = new Set(['id', 'onfinish', 'oncancel', 'onremove']);++/**+ * `saved` for an animation that carries on on the copy of its element:+ * aimed at the copy, without the element's id and event handlers.+ */+function retarget(+ saved: SavedAnimation,+ copyOf: (element: Element) => Element | null,+): SavedAnimation | null {+ const target = saved.target == null ? null : copyOf(saved.target);+ if (target == null) {+ return null;+ }+ const values: Writable = Object.fromEntries(+ Object.entries(saved.values).filter(+ ([name]) => !IDENTITY_MEMBERS.has(name),+ ),+ );+ const effectValues: Writable = {...saved.effectValues};+ if ('target' in effectValues) {+ effectValues.target = target;+ }+ return {...saved, target, values, effectValues};+}++/**+ * Puts each state `saved` holds on the CSS animations and transitions of+ * `root` and its subtree that are not among `survivors`. Each CSS animation+ * the browser started afresh takes the state of the one it replaces. It is+ * matched by element, pseudo-element and name, in order, and then by name+ * alone (an effect script moved to another element or pseudo-element). Each+ * transition whose animation no longer runs resumes as a script animation in+ * its state. One started afresh that replaces none is finished: an entrance+ * that had played and been dropped, or a transition from `@starting-style`.+ * Script animations are left as they are.+ */+export function restoreAnimations(+ root: Element,+ saved: ReadonlyArray<SavedAnimation>,+ survivors: ReadonlySet<Animation>,+): void {+ const after = root.getAnimations({subtree: true});+ const current = new Set(after);+ const cancelled: SavedAnimation[] = [];+ for (const state of saved) {+ if (current.has(state.animation)) {+ continue;+ }+ if (isTransition(state.animation)) {+ resumeTransition(state);+ } else {+ cancelled.push(state);+ }+ }+ const recreated = after.filter(+ animation =>+ (isCssAnimation(animation) || isTransition(animation)) &&+ !survivors.has(animation),+ );+ const unmatched: Animation[] = [];+ for (const animation of recreated) {+ const effect = animation.effect as KeyframeEffect | null;+ const name =+ (animation as Animation & {animationName?: string}).animationName ?? '';+ const index = cancelled.findIndex(+ state =>+ state.name === name &&+ state.target === (effect?.target ?? null) &&+ state.pseudoElement === (effect?.pseudoElement ?? null),+ );+ if (index === -1) {+ unmatched.push(animation);+ } else {+ restore(animation, cancelled.splice(index, 1)[0]);+ }+ }+ for (const animation of unmatched) {+ const name =+ (animation as Animation & {animationName?: string}).animationName ?? '';+ const index = cancelled.findIndex(state => state.name === name);+ if (index === -1) {+ finishIfItEnds(animation);+ } else {+ restore(animation, cancelled.splice(index, 1)[0]);+ }+ }+}++/** The CSS animations and transitions `saveAnimations` read. */+export type SavedAnimations = ReadonlyArray<SavedAnimation>;++/**+ * Reads the state of every CSS animation and transition of `root` and its+ * subtree, for `carryAnimations` to give a copy of it.+ */+export function saveAnimations(root: Element): SavedAnimations {+ if (typeof root.getAnimations !== 'function') {+ return [];+ }+ return root+ .getAnimations({subtree: true})+ .filter(animation => isCssAnimation(animation) || isTransition(animation))+ .map(saveAnimation);+}++/**+ * Carries on in `copy`, a clone of the root `saved` was read from, now laid+ * out, the CSS animations and transitions its element ran. A clone starts+ * each CSS animation again and runs no transition but a `@starting-style`+ * one. So each CSS animation the clone started takes the state of its+ * element's, and each transition runs on as a script animation. One the+ * clone started that its element no longer ran is finished: an entrance that+ * had played, or a `@starting-style` transition. `copyOf` maps each element+ * of the cloned subtree to its copy. The element's own animations keep+ * running, so the copy's take no id or event handler.+ */+export function carryAnimations(+ saved: SavedAnimations,+ copy: Element,+ copyOf: (element: Element) => Element | null,+): void {+ if (typeof copy.getAnimations !== 'function') {+ return;+ }+ restoreAnimations(+ copy,+ saved.flatMap(state => retarget(state, copyOf) ?? []),+ new Set(),+ );+}diff --git a/packages/core/src/motion/transientCopy.ts b/packages/core/src/motion/transientCopy.tsindex 32bb8e6583..b060208bd6 100644--- a/packages/core/src/motion/transientCopy.ts+++ b/packages/core/src/motion/transientCopy.ts@@ -15,9 +15,12 @@* technology, carries no ids or test ids, joins no form or radio group (a* copied checked radio would uncheck the live one), and its frames and media* load nothing. Laying it out changes no ancestor's position, and a scaled- * host draws it at the old size. Laid in a host outside the element's own- * ancestors, it keeps what it inherited from them: its inherited properties- * and custom properties that differ from the host's are written on it.+ * host draws it at the old size. A clone restarts each CSS animation and runs+ * no transition but a `@starting-style` one; the copy carries on its+ * element's from where they were.+ * Laid in a host outside the element's own ancestors, it keeps what it+ * inherited from them: its inherited properties and custom properties that+ * differ from the host's are written on it.* Limits: a rule keyed on a removed `id`, or matched through an ancestor* between the host and the element (`.collapsed .label`), does not style the* copy as it styled the element; and content holding a canvas whose pixels read back@@ -28,6 +31,12 @@* SYNC: When modified, update /packages/core/src/motion/animatedLayout.ts*/+import {+ carryAnimations,+ saveAnimations,+ type SavedAnimations,+} from './carryAnimations';+/** Above this many elements, old content is not copied: the new one enters. */const MAX_COPIED_ELEMENTS = 1500;@@ -151,11 +160,22 @@ const scrollOffsets = new WeakMap<ReadonlyArray<readonly [Element, number, number]>>();+/**+ * The CSS animations and transitions a copy's element ran, and the copy of+ * each element in the copied subtree. The copy carries them on once laid out+ * (`placeOver`).+ */+const carriedMotion = new WeakMap<+ HTMLElement,+ {saved: SavedAnimations; copyOf: ReadonlyMap<Element, Element>}+>();+/*** A copy that takes no part: no ids or test ids, no form or radio group (a* copied checked radio would uncheck the live one), no label for a live* control, and copied frames and media load nothing. Scrolled descendants- * keep their offsets once the copy is laid out (`placeOver`).+ * keep their offsets. The CSS animations and transitions running in it carry+ * on from where they were, once the copy is laid out (`placeOver`).*/export function inertCopy(element: HTMLElement): HTMLElement | null {const copy = element.cloneNode(true) as HTMLElement;@@ -169,6 +189,10 @@ export function inertCopy(element: HTMLElement): HTMLElement | null {});scrollOffsets.set(copy, offsets);inheritedValues.set(copy, readInherited(element));+ carriedMotion.set(copy, {+ saved: saveAnimations(element),+ copyOf: new Map(sourceNodes.map((node, index) => [node, copyNodes[index]])),+ });for (const node of copyNodes) {for (const name of ['id',@@ -215,7 +239,8 @@ export function paintedBackground(element: Element): string {/*** Lay `element` over `rect` (viewport coordinates), absolutely, as the last* child of `host`, wherever its containing block is: no ancestor's position- * changes.+ * changes. A copy's scrolled descendants then restore their offsets, and the+ * CSS animations and transitions its element ran carry on in it.*/export function placeOver(element: HTMLElement,@@ -277,6 +302,15 @@ export function placeOver(node.scrollLeft = left;}}+ const carried = carriedMotion.get(element);+ if (carried != null) {+ carriedMotion.delete(element);+ carryAnimations(+ carried.saved,+ element,+ node => carried.copyOf.get(node) ?? null,+ );+ }}/**@@ -323,6 +357,12 @@ export function visiblePartCopy(element: HTMLElement): {if (values != null) {inheritedValues.set(holder, values);}+ // The content's CSS motion carries on when the holder is laid out.+ const carried = carriedMotion.get(content);+ if (carried != null) {+ carriedMotion.set(holder, carried);+ carriedMotion.delete(content);+ }const box = element.getBoundingClientRect();return {copy: holder,