An open source design system that's fully customizable and agent ready
TypeScript
chore(core): the animator drives a pseudo-element (#8522)
Cindy Zhang57d951bd4b4c
diff --git a/.changeset/uikit-motion-animator-pseudo-element.md b/.changeset/uikit-motion-animator-pseudo-element.mdnew file mode 100644index 0000000000..7ccb10bab3--- /dev/null+++ b/.changeset/uikit-motion-animator-pseudo-element.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the touch presentations' animator drives a pseudo-element such as a dialog's ::backdrop: a static filling animation holds its value after a curve ends and after `set`, a custom property on its host promotes it, and a Reduce Motion dip borrows and hands back the pseudo-element's own opacity. Not exported from the package entry point.++@vjeuxdiff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex f21c4d8aa0..b14dc91c5d 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -81,7 +81,10 @@ await handle.finished; // true if it ran to the end, false if interrupted- Promotion: every animation the animator creates, and every `set`, gives itschannels a compositing layer in the same task (inline `will-change`, mergedwith the element's own), cleared 500 ms after the last motion. Mobile Safari- needs it to run a curve through a blocked main thread.+ needs it to run a curve through a blocked main thread. A pseudo-element is+ promoted through `--astryx-motion-will-change-<pseudo>` on its host; its+ style opts in with+ `willChange: 'var(--astryx-motion-will-change-before, auto)'`.- `atRest(properties)` resolves once none of them is moving, after the lastcurve ends, whoever started it.- `rebase({y: -shift})` moves properties at once, as a layout shift does; a@@ -121,6 +124,13 @@ await handle.finished; // true if it ran to the end, false if interrupted- `animatorFor(element)` returns the one animator for an element, so codethat animates it from several places (a swipe on x, a removal on y)composes in one `translate` track.+- `createAnimator(dialog, {pseudoElement: '::backdrop'})` drives a+ pseudo-element; with no inline style to hold it, a static filling animation+ holds its end value until the next animation replaces it, while the+ pseudo-element exists. A dialog's `::backdrop` is made again each time the+ dialog opens, so a presentation `set`s its starting value right after+ `showModal()`, in the same task (a `set` before it lands on the backdrop+ the open replaces).### How it stays on the compositordiff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex 93a573ddc7..66254c7ce9 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -67,18 +67,23 @@ const requestFrame = (callback: () => void) => {* properties, so the page is modeled here).*/let stylesheet: Record<string, string> = {};+/** The stylesheet's values for a pseudo-element of the element. */+let pseudoStylesheet: Record<string, string> = {};beforeEach(() => {clock = 1000;recorded = [];frameQueue = [];stylesheet = {};+ pseudoStylesheet = {};vi.spyOn(window, 'getComputedStyle').mockImplementation(- element =>+ (element, pseudo) =>({getPropertyValue: (property: string) =>- (element as HTMLElement).style.getPropertyValue(property) ||- (stylesheet[property] ?? ''),+ pseudo != null+ ? (pseudoStylesheet[property] ?? '')+ : (element as HTMLElement).style.getPropertyValue(property) ||+ (stylesheet[property] ?? ''),}) as unknown as CSSStyleDeclaration,);vi.useFakeTimers();@@ -799,6 +804,12 @@ describe('animatorFor: one animator per element', () => {const b = document.createElement('div');expect(animatorFor(a)).toBe(animatorFor(a));expect(animatorFor(a)).not.toBe(animatorFor(b));+ expect(animatorFor(a, {pseudoElement: '::backdrop'})).toBe(+ animatorFor(a, {pseudoElement: '::backdrop'}),+ );+ expect(animatorFor(a, {pseudoElement: '::backdrop'})).not.toBe(+ animatorFor(a),+ );});it('composes two callers’ axes in one translate track', async () => {@@ -902,6 +913,24 @@ describe('promotion: a compositing layer while it moves', () => {expect(element.style.willChange).toBe('');});+ it('promotes a pseudo-element through a custom property on its host', async () => {+ const {animator, element} = setup({pseudoElement: '::backdrop'});+ animator.set({opacity: 0});+ // set() promotes a pseudo-element too.+ expect(+ element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),+ ).toBe('opacity');+ animator.animate({opacity: 1}, {spring: springs.alertPresent});+ expect(+ element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),+ ).toBe('opacity');+ expect(element.style.willChange).toBe('');+ await advance(5000 + PROMOTION_LINGER_MS);+ expect(+ element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),+ ).toBe('');+ });+it('ends promotion on the element it leaves', () => {const {animator, element} = setup();animator.animate({x: 50}, {spring: springs.settle});@@ -1937,6 +1966,75 @@ describe('Reduced Motion (design:reduced-motion)', () => {expect(element.style.translate).toBe('100px 0px');});+ it("a pseudo-element's dip borrows its own opacity and hands it back without touching the host", async () => {+ for (const role of [undefined, 'exit'] as const) {+ const {animator, element} = setup({+ reduced: true,+ coarse: true,+ pseudoElement: '::before',+ });+ element.style.opacity = '0.5'; // the host's own, untouched+ pseudoStylesheet = {opacity: '0.3'};+ animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ role == null ? {} : {crossfadeAs: role},+ );+ await commitFrame(clock);+ const [fadeLayer] = live('opacity');+ const values = fadeLayer.keyframes.map(k => Number(k.opacity));+ expect(Math.max(...values)).toBeCloseTo(0.3, 9);+ await advance(fade * 2 + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(100);+ // The pseudo-element's stylesheet owns its opacity again; the host+ // keeps its own.+ expect(live('opacity')).toEqual([]);+ expect(element.style.opacity).toBe('0.5');+ }+ });++ it("a pseudo-element's identity hold follows a node replacement", () => {+ const {animator, element} = setup({pseudoElement: '::backdrop'});+ pseudoStylesheet = {opacity: '0'};+ animator.set({opacity: 1});+ animator.attach(null);+ const next = document.createElement('div');+ document.body.append(next);+ animator.attach(next);+ const held = live('opacity').filter(+ animation => animation.element === next,+ );+ expect(held).toHaveLength(1);+ expect(Number(held[0].keyframes.at(-1)!.opacity)).toBe(1);+ expect(live('opacity').some(a => a.element === element)).toBe(false);+ next.remove();+ });++ it('a pseudo-element shown over a hiding stylesheet keeps its own opacity through a move', async () => {+ for (const role of [undefined, 'entrance'] as const) {+ const {animator} = setup({+ reduced: true,+ coarse: true,+ pseudoElement: '::backdrop',+ });+ pseudoStylesheet = {opacity: '0'};+ animator.set({opacity: 1});+ animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ role == null ? {} : {crossfadeAs: role},+ );+ await commitFrame(clock);+ for (let step = 0; step < 8; step++) {+ await advance(fade / 4);+ }+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBe(1);+ const [held] = live('opacity');+ expect(Number(held.keyframes.at(-1)?.opacity)).toBe(1);+ }+ });+it('a move dips: fades out, lands while transparent, fades back in', async () => {const {animator, element} = reduced();animator.animate({x: 100}, {spring: springs.navigationPush});@@ -2555,6 +2653,56 @@ describe('decay: momentum curves (a coast)', () => {});});+describe('pseudoElement: a dialog\u2019s ::backdrop', () => {+ it('targets the pseudo-element, writes no inline style and holds the end state', async () => {+ const {animator, element} = setup({pseudoElement: '::backdrop'});+ animator.set({opacity: 0});+ const [held] = live('opacity');+ expect(held.options).toMatchObject({+ fill: 'both',+ pseudoElement: '::backdrop',+ });+ expect(held.keyframes.map(k => k.opacity)).toEqual(['0', '0']);+ expect(element.style.opacity).toBe('');++ animator.animate({opacity: 1}, {spring: springs.alertPresent});+ // The new animation exists before the hold goes: no frame in between.+ expect(held.cancelled).toBe(true);+ const [fade] = live('opacity');+ expect(fade.options).toMatchObject({+ fill: 'both',+ pseudoElement: '::backdrop',+ });+ expect(fade.keyframes[fade.keyframes.length - 1].opacity).toBe('1');+ expect(element.style.opacity).toBe('');+ await advance(Number(fade.options.duration) + 1000);+ // Past the curve's end, a static animation holds the end value.+ expect(fade.cancelled).toBe(true);+ const [rest] = live('opacity');+ expect(rest.options).toMatchObject({+ fill: 'both',+ pseudoElement: '::backdrop',+ });+ expect(rest.keyframes.map(k => k.opacity)).toEqual(['1', '1']);+ expect(animator.get('opacity')).toBe(1);+ });++ it('an exit holds 0 until the next animation replaces it', async () => {+ const {animator} = setup({+ pseudoElement: '::backdrop',+ initial: {opacity: 1},+ });+ animator.animate({opacity: 0}, {spring: springs.alertDismiss});+ const [fade] = live('opacity');+ await advance(Number(fade.options.duration) + 1000);+ const [rest] = live('opacity');+ expect(rest.keyframes.map(k => k.opacity)).toEqual(['0', '0']);+ animator.animate({opacity: 1}, {spring: springs.alertPresent});+ expect(rest.cancelled).toBe(true);+ expect(live('opacity')).toHaveLength(1);+ });+});+describe('attach', () => {it('keeps state without an element and resumes the curve on attach', () => {const animator = createAnimator(null, {diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 767dec344f..cb539e0d87 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -69,13 +69,17 @@* Chromium starts it after the block.** Promotion: Mobile Safari runs an animation whose start time is set from- * script on its compositor at its first commit only if the element already- * has a compositing layer; without one, a block right after that commit- * freezes it (iOS 26.2 simulator: 2 of 7 runs kept moving). Every animation- * the animator creates, and every `set`, therefore promotes its channels in- * the same task: inline `will-change` on the element, merged with the- * element's own. That is enough (5 of 5, and 4 of 4 through the animator);- * promotion ends PROMOTION_LINGER_MS after the last motion.+ * script on its compositor at its first commit only if the element (or the+ * pseudo-element) already has a compositing layer; without one, a block+ * right after that commit freezes it (iOS 26.2 simulator: 2 of 7 runs kept+ * moving, 0 of 5 on a ::before). Every animation the animator creates, and+ * every `set`, therefore promotes its channels in the same task: inline+ * `will-change` on the element, merged with the element's own, or the custom+ * property `--astryx-motion-will-change-<pseudo>` on the host for a+ * pseudo-element, whose style opts in with+ * `will-change: var(--astryx-motion-will-change-before, auto)`. That is+ * enough (5 of 5, and 4 of 4 through the animator); promotion ends+ * PROMOTION_LINGER_MS after the last motion.** Known limits, iOS Safari (measured on the iOS 26.2 simulator):* - a block in the task that starts a motion delays it: it starts when the@@ -125,6 +129,14 @@* Motion policy above, a cross-fade on a coarse pointer or after a touch* release (`touchRelease`) and at once elsewhere (DR2, DR3).*+ * A pseudo-element (`options.pseudoElement`, a dialog's `::backdrop`) has no+ * inline style: its end value is held by a static filling animation (after a+ * curve ends, and after `set`) until the next animation replaces it, and for+ * as long as the pseudo-element exists. The browser makes a `::backdrop`+ * again each time its dialog opens, without the hold, so a presentation+ * calls `set` with its starting value right after `showModal()`, in the same+ * task: a `set` before it lands on the backdrop the open replaces.+ ** SSR-safe: nothing touches `window` or `document` at module scope, and an* animator created without an element only keeps state until one is attached.*@@ -220,6 +232,12 @@ export interface MotionCurve {* Options of `createAnimator`.*/export interface AnimatorOptions {+ /**+ * Animates a pseudo-element of the element instead (`'::backdrop'` of a+ * native dialog). A pseudo-element has no inline style, so a static filling+ * animation holds its value after a curve ends and after `set`.+ */+ pseudoElement?: string;/** Starting values; identity by default. Never read from the DOM. */initial?: MotionValues;/** Clock in ms on the document timeline's time base. */@@ -558,10 +576,10 @@ function format(}}-const shared = new WeakMap<HTMLElement, Animator>();+const shared = new WeakMap<HTMLElement, Map<string, Animator>>();/**- * The one animator for `element`, created on+ * The one animator for `element` (and `options.pseudoElement`), created on* first use. Code that animates one element from several places (a swipe on* x, a removal on y) shares it, so their curves compose in one `translate`* track and retargeting one axis leaves the other on its curve; two@@ -573,10 +591,16 @@ export function animatorFor(element: HTMLElement,options: AnimatorOptions = {},): Animator {- let animator = shared.get(element);+ let byPseudo = shared.get(element);+ if (byPseudo == null) {+ byPseudo = new Map();+ shared.set(element, byPseudo);+ }+ const key = options.pseudoElement ?? '';+ let animator = byPseudo.get(key);if (animator == null) {animator = createAnimator(element, options);- shared.set(element, animator);+ byPseudo.set(key, animator);}return animator;}@@ -712,6 +736,7 @@ export function createAnimator(requestAnimationFrame(() => callback());}: null);+ const pseudoElement = options.pseudoElement;// Reduced Motion reads the person's settings and nothing else: no option// overrides them (design:reduced-motion DR4).const prefersReducedMotion = defaultPrefersReducedMotion;@@ -762,6 +787,11 @@ export function createAnimator(/** The stylesheet's will-change when there is no inline value. */let sheetWillChange = '';let demoteTimer: ReturnType<typeof setTimeout> | null = null;+ /** A pseudo-element is promoted through a custom property on its host. */+ const promotionProperty =+ pseudoElement == null+ ? null+ : `--astryx-motion-will-change-${pseudoElement.replace(/^:+/, '')}`;/** Channels whose identity the last node held inline (see `attach`). */let heldIdentity = new Set<Channel>();@@ -843,7 +873,7 @@ export function createAnimator(channel: Channel,value: (property: MotionProperty) => number,) => {- if (target == null) {+ if (target == null || pseudoElement != null) {return;}touched.add(channel);@@ -908,14 +938,32 @@ export function createAnimator(return times;};+ /** A pseudo-element's resting value, held by a static filling animation. */+ const hold = (channel: Channel, time: number) => {+ if (target == null) {+ return;+ }+ const value = format(channel, finalValue);+ const animation = target.animate([{[channel]: value}, {[channel]: value}], {+ duration: 1,+ fill: 'both',+ pseudoElement,+ });+ animation.startTime = time;+ running.set(channel, animation);+ };+const rebuild = (channel: Channel, time: number) => {const previous = running.get(channel);running.delete(channel);clearTimeout(retireTimers.get(channel));retireTimers.delete(channel);- // The element's inline style holds the end state, so its old animation- // can go first.- previous?.cancel();+ // An element's inline style holds the end state, so its old animation can+ // go first. A pseudo-element has none: its old animation keeps holding the+ // value until the new one exists (same task, no frame in between).+ if (pseudoElement == null) {+ previous?.cancel();+ }const properties = CHANNELS[channel];// Settled curves become resting values.for (const property of properties) {@@ -932,6 +980,10 @@ export function createAnimator(return;}if (moving.length === 0) {+ if (pseudoElement != null) {+ hold(channel, time);+ }+ previous?.cancel();return;}// A channel rebuilt by an explicit call (set, rebase, a retarget of@@ -958,6 +1010,10 @@ export function createAnimator(),);if (end <= from) {+ if (pseudoElement != null) {+ hold(channel, time);+ }+ previous?.cancel();return;}if (callGroup != null) {@@ -1041,6 +1097,7 @@ export function createAnimator(// inline style already holds the same values, so that changes no pixel.fill: 'both',easing: 'linear',+ ...(pseudoElement != null ? {pseudoElement} : {}),});if (waiting != null) {// From rest: no start time, so the browser starts the animation when@@ -1061,7 +1118,9 @@ export function createAnimator(/*** Once the main thread runs after the curve's end, the animation leaves the- * running state: the element's inline style already shows the end values.+ * running state: an element's inline style already shows the end values; a+ * pseudo-element's end value moves to a static holding animation, created+ * before the long one goes.*/const scheduleRetire = (channel: Channel,@@ -1088,6 +1147,15 @@ export function createAnimator(return;}running.delete(channel);+ // A pseudo-element holds its resting value, unless the stylesheet+ // takes it back now (a borrowed dip that has ended).+ const handsBack =+ channel === 'opacity' &&+ borrowedOpacity != null &&+ ![...landings].some(landing => landing.fadeIn?.isBorrowed === true);+ if (pseudoElement != null && !handsBack) {+ hold(channel, now());+ }animation.cancel();releaseIdentity(channel);flushReleases();@@ -1102,22 +1170,36 @@ export function createAnimator(target == null? NaN: Number.parseFloat(- view?.getComputedStyle(target).getPropertyValue('opacity') ?? '',+ view+ ?.getComputedStyle(target, pseudoElement ?? null)+ .getPropertyValue('opacity') ?? '',);return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;};/*** Whether the animator holds an opacity of its own on the element: an inline- * value it wrote (a `set` over a stylesheet that hides or dims it). A dip- * returns to that value.+ * value it wrote, or a pseudo-element's holding animation (a `set` over a+ * stylesheet that hides or dims it). A dip returns to that value.*/const writesOwnOpacity = (): boolean =>- (target?.style.getPropertyValue('opacity') ?? '') !== '';+ pseudoElement == null+ ? (target?.style.getPropertyValue('opacity') ?? '') !== ''+ : running.has('opacity');- /** Gives the element's opacity back to its stylesheet: its inline value goes. */+ /**+ * Gives the element's opacity back to its stylesheet: an element's inline+ * value goes; a pseudo-element, which has no inline style, loses the+ * animation holding its value.+ */const releaseOwnOpacity = () => {- target?.style.removeProperty('opacity');+ if (pseudoElement == null) {+ target?.style.removeProperty('opacity');+ return;+ }+ const held = running.get('opacity');+ running.delete('opacity');+ held?.cancel();};/**@@ -1202,6 +1284,9 @@ export function createAnimator(releaseOwnOpacity();return;}+ if (pseudoElement != null) {+ return;+ }if (target.style.getPropertyValue(channel) !== IDENTITY_TEXT[channel]) {return;}@@ -1265,9 +1350,17 @@ export function createAnimator(// -- promotion -------------------------------------------------------------- /** Writes the promoted channels as will-change. */+ /** Writes the promoted channels as will-change (or the pseudo's property). */const writePromotion = (element: HTMLElement) => {const list = [...promoted].join(', ');+ if (promotionProperty != null) {+ if (list === '') {+ element.style.removeProperty(promotionProperty);+ } else {+ element.style.setProperty(promotionProperty, list);+ }+ return;+ }if (list === '') {element.style.willChange = ownWillChange ?? '';ownWillChange = null;@@ -1294,7 +1387,7 @@ export function createAnimator(};/**- * Gives the element a compositing layer for+ * Gives the element (or its pseudo-element) a compositing layer for* `channel` from the task that starts the motion: Mobile Safari runs an* animation whose start time is set from script on its compositor at its* first commit only if the element already has a layer.@@ -2226,9 +2319,25 @@ export function createAnimator(}// After the landing's commit, which can promote the element again.demote();+ // A pseudo-element holds an identity with a static animation, which the+ // cancel below drops: note the channels to hold again on the next node+ // (never a borrowed opacity, which is the stylesheet's).const isOpacityBorrowed =borrowedOpacity != null ||[...landings].some(landing => landing.restoreIsBorrowed === true);+ const pseudoHeld =+ pseudoElement == null || target == null+ ? null+ : new Set(+ (Object.keys(CHANNELS) as Channel[]).filter(+ channel =>+ running.has(channel) &&+ !(channel === 'opacity' && isOpacityBorrowed) &&+ CHANNELS[channel].every(+ p => !segments.has(p) && resting[p] === IDENTITY[p],+ ),+ ),+ );for (const animation of running.values()) {animation.cancel();}@@ -2248,13 +2357,15 @@ export function createAnimator(// differs, kept through a detach for the node that comes next.if (target != null) {const outgoing = target;- heldIdentity = new Set(- (Object.keys(CHANNELS) as Channel[]).filter(- channel =>- outgoing.style.getPropertyValue(channel) ===- IDENTITY_TEXT[channel],- ),- );+ heldIdentity =+ pseudoHeld ??+ new Set(+ (Object.keys(CHANNELS) as Channel[]).filter(+ channel =>+ outgoing.style.getPropertyValue(channel) ===+ IDENTITY_TEXT[channel],+ ),+ );}const held = heldIdentity;target = next;@@ -2284,8 +2395,13 @@ export function createAnimator(} else if (held.has(channel)) {// An identity the animator held inline over a stylesheet that// differs goes onto the new node too (writeInline keeps it only- // where the new node's stylesheet still differs).- writeInline(channel, property => resting[property]);+ // where the new node's stylesheet still differs); a pseudo-element's+ // is held again.+ if (pseudoElement != null) {+ hold(channel, time);+ } else {+ writeInline(channel, property => resting[property]);+ }}}flushReleases();