An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a Switch at rest holds no compositing layer (#10542)
Christopher Chedeauafcba3b79476
diff --git a/.changeset/motion-a-switch-at-rest-holds-no-compositing-lay-fv55.md b/.changeset/motion-a-switch-at-rest-holds-no-compositing-lay-fv55.mdnew file mode 100644index 0000000000..edc558734b--- /dev/null+++ b/.changeset/motion-a-switch-at-rest-holds-no-compositing-lay-fv55.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[perf] Motion: a Switch at rest holds no compositing layer under a coarse pointer. Its colour fade and its lift's shadow take a layer only while they move.+@vjeuxdiff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex 6f291bf4ef..8e18e1cc58 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -460,9 +460,13 @@ const styles = stylex.create({pointerEvents: 'none',opacity: 0,backgroundColor: 'var(--_switch-fade-fill, transparent)',- // Its own compositing layer from the start, so its fade runs off the- // main thread (iOS Safari otherwise animates it on the main thread).- willChange: {default: null, [TOUCH]: 'opacity'},+ // A compositing layer only while a fade runs. The animator sets the+ // property in the task that starts the fade: iOS Safari needs that to+ // run the fade off the main thread. It clears it after the fade rests.+ willChange: {+ default: null,+ [TOUCH]: 'var(--astryx-motion-will-change-after, auto)',+ },},},// The one ring in the system not drawn by focusOutlineStyles. The focusable@@ -629,7 +633,12 @@ const styles = stylex.create({pointerEvents: 'none',opacity: 0,boxShadow: shadowVars['--shadow-low'],- willChange: {default: null, [TOUCH]: 'opacity'},+ // A compositing layer only while the lift fades the shadow, as for the+ // track's colour fade.+ willChange: {+ default: null,+ [TOUCH]: 'var(--astryx-motion-will-change-after, auto)',+ },},// Pressed with a mouse: the same overlay as the track, so the whole// control darkens rather than the thumb standing out against a darkerdiff --git a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.tsindex 4ea562947a..5b8519dce3 100644--- a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts+++ b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts@@ -64,6 +64,7 @@ import {} from '@astryxdesign/interaction-harness';import {BROWSER_CLICK_WAIT_MS} from '../../utils/browserClickWait';import {CLICK_GUARD_WINDOW_MS} from '../../utils/clickGuard';+import {PROMOTION_LINGER_MS} from '../../motion/animator';const storybook = withStorybook(test);@@ -626,6 +627,173 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',expect(await visibleFill(page)).toBe(expected.on);});+ test('a page of switches holds no compositing layer at rest, and a toggled switch gives its layers back once it rests', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'The count reads Chromium’s layer tree through the DevTools protocol.',+ );+ const cdp = await page.context().newCDPSession(page);+ let layers = 0;+ cdp.on('LayerTree.layerTreeDidChange', event => {+ if (event.layers != null) {+ layers = event.layers.length;+ }+ });+ await cdp.send('LayerTree.enable');+ const {driver, input, thumb, center} = await openSwitch(+ page,+ 'core-switch--in-scrolling-list',+ );+ // The tree after a wait and two frames, so it holds what they drew.+ const count = async (waitMs: number) => {+ await page.waitForTimeout(waitMs);+ await page.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+ return layers;+ };+ const atRest = await count(PROMOTION_LINGER_MS + 200);+ const wasOn = await input.isChecked();+ await driver.play(tap(center));+ await expect(input).toBeChecked({checked: !wasOn});+ await waitForSwitchRest(page, thumb);+ // The fade and the shadow's settle end within a second of the thumb.+ const afterToggle = await count(1000 + PROMOTION_LINGER_MS);+ // The same page without its switches: what they add.+ await page.evaluate(() =>+ document.querySelector('#storybook-root > div')?.replaceChildren(),+ );+ const bare = await count(300);+ expect(+ atRest - bare,+ `24 switches at rest hold ${atRest - bare} layers`,+ ).toBe(0);+ expect(+ afterToggle - bare,+ `the toggled switch holds ${afterToggle - bare} layers after it rests`,+ ).toBe(0);+ });++ test('a toggle promotes its fade, its travel and its shadow by their first frame, and drops them only after they rest', async ({+ page,+ }) => {+ const {driver, input, center} = await openSwitch(page);+ await page.evaluate(() => {+ const track = document.querySelector(+ '#storybook-root .astryx-switch',+ ) as HTMLElement;+ const thumb = document.querySelector(+ '#storybook-root .astryx-switch-thumb',+ ) as HTMLElement;+ // A curve the element or pseudo-element moves on: a hold lasts 1 ms.+ const moves = (+ element: HTMLElement,+ pseudo: string | null,+ property: string,+ ) =>+ element.getAnimations({subtree: true}).some(animation => {+ const effect = animation.effect as KeyframeEffect;+ return (+ effect.target === element &&+ (effect.pseudoElement ?? null) === pseudo &&+ Number(effect.getTiming().duration) > 1 &&+ effect.getKeyframes().some(frame => property in frame)+ );+ });+ const w = window as unknown as {+ __promotion: {+ t: number;+ fade?: string;+ travel?: string;+ shadow?: string;+ }[];+ };+ w.__promotion = [];+ const start = performance.now();+ const tick = () => {+ w.__promotion.push({+ t: performance.now() - start,+ fade: moves(track, '::after', 'opacity')+ ? getComputedStyle(track, '::after').willChange+ : undefined,+ travel: moves(thumb, null, 'translate')+ ? getComputedStyle(thumb).willChange+ : undefined,+ shadow: moves(thumb, '::after', 'opacity')+ ? getComputedStyle(thumb, '::after').willChange+ : undefined,+ });+ if (performance.now() - start < 3000) {+ requestAnimationFrame(tick);+ }+ };+ requestAnimationFrame(tick);+ });+ await driver.play(tap(center));+ await expect(input).toBeChecked();+ await page.waitForFunction(+ () =>+ ((window as unknown as {__promotion: {t: number}[]}).__promotion.at(-1)+ ?.t ?? 0) >= 3000,+ );+ const frames = await page.evaluate(+ () =>+ (+ window as unknown as {+ __promotion: {+ t: number;+ fade?: string;+ travel?: string;+ shadow?: string;+ }[];+ }+ ).__promotion,+ );+ for (const [kind, property] of [+ ['fade', 'opacity'],+ ['travel', 'translate'],+ ['shadow', 'opacity'],+ ] as const) {+ const moving = frames.filter(frame => frame[kind] != null);+ expect(moving.length, `the ${kind} moved on no frame`).toBeGreaterThan(0);+ // From its first frame to its last, it has a layer.+ for (const frame of moving) {+ expect(+ frame[kind],+ `the ${kind} at ${Math.round(frame.t)} ms`,+ ).toContain(property);+ }+ // At the end it rests: no curve, so no layer.+ expect(+ frames[frames.length - 1][kind],+ `the ${kind} at the end`,+ ).toBeUndefined();+ }+ const resting = await page.evaluate(() => {+ const track = document.querySelector(+ '#storybook-root .astryx-switch',+ ) as HTMLElement;+ const thumb = document.querySelector(+ '#storybook-root .astryx-switch-thumb',+ ) as HTMLElement;+ return [+ getComputedStyle(track, '::after').willChange,+ getComputedStyle(thumb).willChange,+ getComputedStyle(thumb, '::after').willChange,+ ];+ });+ expect(+ resting,+ 'will-change at rest: the track’s ::after, the thumb, its ::after',+ ).toEqual(['auto', 'auto', 'auto']);+ });+test('P1 · a tap toggles at the release: the thumb travels and the track turns on, and the lift settles back', async ({page,}) => {diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.tsindex fcdbf2cff5..38d1f3b171 100644--- a/packages/core/src/Switch/useSwitchTouch.ts+++ b/packages/core/src/Switch/useSwitchTouch.ts@@ -194,8 +194,9 @@ interface Drag {* fade already heads to swaps nothing: the track holds its previous fill* inline until the fade lands. WebKit plays a curve built in a held frame* only once the long task ends, so a swap there stepped the colour back.- * The layer is composited from the start (`will-change`, Switch.tsx), or- * iOS Safari runs its fade on the main thread.+ * The animator promotes the layer in the task that starts its fade, as+ * iOS Safari needs, and demotes it after the fade rests. At rest no part+ * of the switch holds a compositing layer.* - Under reduced motion nothing travels or springs: a change plays the* animator's Reduce Motion cross-fade. A dragging finger still moves the* thumb: that is direct manipulation.@@ -286,17 +287,22 @@ export class SwitchTouchController {registerSwitchTable();this.thumb = createMotionEngine(elements.thumb);// The layer rests clear (its class's opacity 0) while the visuals show- // the value; from here its opacity is the animator's.+ // the value; from here its opacity is the animator's. The stylesheet+ // shows that rest (`base`), so no animation holds it there. These writes+ // promote nothing: a page of switches holds no compositing layer until+ // one moves.this.fade = createMotionEngine(elements.track, {pseudoElement: '::after',initial: {opacity: 0},+ base: {opacity: 0},});- this.fade.set({opacity: 0});+ this.fade.set({opacity: 0}, {promote: false});this.shadow = createMotionEngine(elements.thumb, {pseudoElement: '::after',initial: {opacity: 0},+ base: {opacity: 0},});- this.shadow.set({opacity: 0});+ this.shadow.set({opacity: 0}, {promote: false});this.paintFade();this.detachers = this.attachPassive(host, elements);}@@ -381,7 +387,7 @@ export class SwitchTouchController {setGeometry(geometry: SwitchTouchGeometry): void {this.geometry = geometry;this.measureGeometry();- this.thumb?.set({x: 0, scaleX: 1, scaleY: 1});+ this.thumb?.set({x: 0, scaleX: 1, scaleY: 1}, {promote: false});}/**diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 5d7cec1464..d21e026ea6 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -181,7 +181,10 @@ await handle.finished; // true if it ran to the end, false if interrupted- `createMotionEngine(dialog, {pseudoElement: '::backdrop'})` drives apseudo-element; with no inline style to hold it, a static filling animationholds its end value until the next animation replaces it, while the- pseudo-element exists. A dialog's `::backdrop` is made again each time the+ pseudo-element exists. A value equal to its `base` (`{base: {opacity: 0}}`,+ what its stylesheet shows at rest) is not held, so the pseudo-element keeps+ no compositing layer at rest; in development, the first such value warns+ when the stylesheet shows another. A dialog's `::backdrop` is made again each time thedialog opens, so a presentation `set`s its starting value right after`showModal()`, in the same task (a `set` before it lands on the backdropthe open replaces).diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex e03b4defe8..e4cd8c8a35 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -4264,6 +4264,112 @@ describe('pseudoElement: a dialog\u2019s ::backdrop', () => {});});+describe('base: what a pseudo-element\u2019s stylesheet shows at rest', () => {+ const clear = {+ pseudoElement: '::after',+ initial: {opacity: 0},+ base: {opacity: 0},+ } as const;++ it('a value at its base leaves no holding animation, and any other value still holds', async () => {+ const {animator} = setup(clear);+ animator.set({opacity: 0});+ expect(live('opacity')).toHaveLength(0);+ animator.set({opacity: 0.5});+ const [held] = live('opacity');+ expect(held.keyframes.map(k => k.opacity)).toEqual(['0.5', '0.5']);++ animator.animate({opacity: 0}, {spring: springs.alertDismiss});+ expect(held.cancelled).toBe(true);+ const [fade] = live('opacity');+ await advance(Number(fade.options.duration) + 1000);+ // Past the curve's end the stylesheet shows the base: nothing holds it.+ expect(fade.cancelled).toBe(true);+ expect(live('opacity')).toHaveLength(0);+ expect(animator.get('opacity')).toBe(0);++ animator.animate({opacity: 1}, {spring: springs.alertPresent});+ const [rise] = live('opacity');+ await advance(Number(rise.options.duration) + 1000);+ // An end other than the base is held, as with no base.+ const [rest] = live('opacity');+ expect(rest.keyframes.map(k => k.opacity)).toEqual(['1', '1']);+ });++ it('a curve that settles to within the sampling tolerance of its base leaves no hold', async () => {+ const {animator} = setup(clear);+ // Seconds, as a curve's time is.+ const settlingTo = (end: number) => ({+ duration: 0.3,+ at: (t: number) => 1 + (end - 1) * Math.min(1, t / 0.3),+ velocity: () => 0,+ });+ animator.play({opacity: settlingTo(0.001)});+ await advance(1300);+ expect(live('opacity')).toHaveLength(0);+ animator.play({opacity: settlingTo(0.01)});+ await advance(1300);+ const [held] = live('opacity');+ expect(held.keyframes.map(k => k.opacity)).toEqual(['0.01', '0.01']);+ });++ it('a node replaced at rest holds nothing at its base', () => {+ const {animator} = setup(clear);+ animator.set({opacity: 0});+ animator.attach(document.createElement('div'));+ expect(live('opacity')).toHaveLength(0);+ animator.set({opacity: 0.5});+ animator.attach(document.createElement('div'));+ const held = live('opacity');+ expect(held).toHaveLength(1);+ expect(held[0].keyframes.map(k => k.opacity)).toEqual(['0.5', '0.5']);+ });++ it('a Reduce Motion dip that lands on its base leaves no opacity animation', async () => {+ const {animator} = setup({+ reduced: true,+ coarse: true,+ pseudoElement: '::after',+ base: {opacity: 1},+ });+ animator.set({opacity: 1});+ expect(live('opacity')).toHaveLength(0);+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ expect(live('opacity').length).toBeGreaterThan(0);+ await advance(END_HOLD_MS + 5000);+ expect(animator.get('x')).toBe(100);+ expect(live('opacity')).toHaveLength(0);+ });++ it('in development, the first hold it drops warns once when the stylesheet shows another value', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ pseudoStylesheet = {opacity: '1'};+ const {animator} = setup(clear);+ animator.set({opacity: 0});+ // The read waits for a later task.+ expect(warn).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(warn).toHaveBeenCalledTimes(1);+ expect(String(warn.mock.calls[0][0])).toMatch(+ /::after stylesheet shows opacity 1, not its declared base 0/,+ );+ animator.set({opacity: 0.5});+ animator.set({opacity: 0});+ await vi.advanceTimersByTimeAsync(1);+ expect(warn).toHaveBeenCalledTimes(1);+ });++ it('a stylesheet that shows its base raises no warning', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ pseudoStylesheet = {opacity: '0'};+ const {animator} = setup(clear);+ animator.set({opacity: 0});+ await vi.advanceTimersByTimeAsync(1);+ expect(warn).not.toHaveBeenCalled();+ });+});+describe('attach', () => {it('keeps state without an element and resumes the curve on attach', () => {const animator = createMotionEngine(null, {diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex b363d7fee7..906abe3868 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -163,12 +163,16 @@* a role.** 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.+ * inline style. A static filling animation holds its end value, after a+ * curve ends and after `set`, until the next animation replaces it. The hold+ * lasts as long as the pseudo-element exists. A value equal to its `base`,+ * the values its own stylesheet shows at rest, is not held. The stylesheet+ * shows it, so the pseudo-element keeps no compositing layer at rest. In+ * development, the first hold dropped this way checks that the stylesheet+ * shows it. The browser makes a `::backdrop` again, without the hold, each+ * time its dialog opens. 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.@@ -197,6 +201,9 @@ import {} from './uikit/timing';import {planReducedMotion, type ReducedMotionView} from './reducedMotionPlan';import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';+import {devWarn} from '../utils/devWarning';++declare const process: {readonly env: {readonly NODE_ENV?: string}};/*** A value the animator can drive.@@ -343,12 +350,21 @@ export interface SetOptions {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`.+ * native dialog). A pseudo-element has no inline style. So a static filling+ * animation holds its value after a curve ends and after `set`, unless the+ * value is its `base`.*/pseudoElement?: string;/** Starting values; identity by default. Never read from the DOM. */initial?: MotionValues;+ /**+ * For a pseudo-element: the values its own stylesheet shows at rest. A+ * value equal to its base needs no holding animation, so the+ * pseudo-element keeps no compositing layer there. Declare only what the+ * stylesheet shows: in development, the first hold dropped warns when the+ * computed style differs.+ */+ base?: MotionValues;/** Clock in ms on the document timeline's time base. */now?: () => number;/**@@ -816,6 +832,33 @@ function format(}}+/**+ * Whether a computed value shows `expected` (`format`'s text). An unset or+ * `none` value is the channel's identity. One value of a two-value channel+ * stands for both (scale), or for x with y at 0 (translate).+ */+function sameShown(channel: Channel, shown: string, expected: string): boolean {+ const numbers = (text: string): number[] => {+ const values = (+ text === '' || text === 'none' ? IDENTITY_TEXT[channel] : text+ ).match(/-?\d*\.?\d+(?:e-?\d+)?/g);+ const list = (values ?? []).map(Number);+ if (channel === 'translate') {+ return [list[0] ?? 0, list[1] ?? 0];+ }+ if (channel === 'scale') {+ return [list[0] ?? 1, list[1] ?? list[0] ?? 1];+ }+ return list.length > 0 ? list : [channel === 'opacity' ? 1 : 0];+ };+ const a = numbers(shown);+ const b = numbers(expected);+ return (+ a.length === b.length &&+ a.every((value, i) => Math.abs(value - b[i]) < 1e-3)+ );+}+const shared = new WeakMap<HTMLElement, Map<string, Animator>>();/**@@ -1003,6 +1046,7 @@ export function createMotionEngine(...IDENTITY,...expand(options.initial ?? {}),};+ const base = expand(options.base ?? {});const segments = new Map<MotionProperty, Segment>();const running = new Map<Channel, Animation>();/** Drops a finished, still-filling animation once the main thread runs. */@@ -1381,11 +1425,63 @@ export function createMotionEngine(return times;};- /** A pseudo-element's resting value, held by a static filling animation. */+ /**+ * Whether the pseudo-element's stylesheet shows the channel's resting+ * value: its base, to within the sampling tolerance, which no frame shows.+ * A curve that settles to a threshold ends that close to its target.+ */+ const atBase = (channel: Channel) =>+ CHANNELS[channel].every(property => {+ const value = base[property];+ return (+ value != null &&+ Math.abs(finalValue(property) - value) <= SAMPLE_TOLERANCE[property]+ );+ });++ let baseChecked = false;+ /**+ * The first hold dropped at `base` checks, in development, that the+ * stylesheet shows it. It reads after the cancel and off the motion's task,+ * so it adds no style read to a frame that starts a motion.+ */+ const checkBase = (channel: Channel) => {+ if (process.env.NODE_ENV === 'production' || baseChecked) {+ return;+ }+ baseChecked = true;+ setTimeout(() => {+ if (target == null) {+ return;+ }+ const shown = getComputedStyle(target, pseudoElement).getPropertyValue(+ channel,+ );+ const expected = format(channel, p => base[p] ?? IDENTITY[p]);+ if (!sameShown(channel, shown, expected)) {+ devWarn(+ 'Astryx motion',+ `the ${pseudoElement} stylesheet shows ${channel} ` ++ `${shown || '(unset)'}, not its declared base ${expected}, so ` ++ 'it shows the wrong value at rest. Make `base` match the ' ++ 'stylesheet.',+ );+ }+ }, 0);+ };++ /**+ * A pseudo-element's resting value, held by a static filling animation,+ * unless its stylesheet shows it (`base`).+ */const hold = (channel: Channel, time: number) => {if (target == null) {return;}+ if (atBase(channel)) {+ checkBase(channel);+ return;+ }const value = format(channel, finalValue);const animation = target.animate([{[channel]: value}, {[channel]: value}], {duration: 1,