Commit 40f2dc23883 for woocommerce

commit 40f2dc238836b482afc119a9aa8d9158e4783b3f
Author: Mike Jolley <mike.jolley@me.com>
Date:   Thu Nov 26 12:58:24 2026 +0000

    Add motion to the coupon panel (#70883)

    * Grow and collapse Panel content in Cart and Checkout

    Adds animateCollapse and the motion-collapse mixin, and a collapse
    option on usePresence. The gap under the panel button transitions with
    the content. Key presses apply immediately.

    * Add this PR's helpers and lessons to the Motion guide

    * Leave no empty style attribute after a collapse

    Chrome re-creates style="" when the cleared inline styles have not been
    read before the attribute is removed. Reading it first removes it for good.

    * Grow on to the new size when collapse content resizes mid-grow

    The grow ends at the height measured when it starts. If the content changed size during the grow, removing the inline styles at the end made the element jump to its new height. When the grow ends, it now grows on from the held size to the new natural size, and stops once nothing differs.

    * Stop a running grow when animate turns off in usePresence

    Keyboard updates mid-grow now apply at once instead of letting the grow finish or regrow.

    * Give each collapse transition its own animation in the test fake

    The fake had one transition, so the continuation of a grow had nothing to wait for and the test could not catch cleanup that ran too early. Each start now replaces the running transition, as in a browser.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Share the inline style cleanup and simplify the presence grow

    `clearInlineStyle` removes inline styles and an empty `style` attribute, for the other motion helpers to reuse. `usePresence` calls `animateCollapse` from one branch, and the Panel uses `exitingProps`.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    ---------

    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/plugins/woocommerce/changelog/add-cart-checkout-motion-collapse b/plugins/woocommerce/changelog/add-cart-checkout-motion-collapse
new file mode 100644
index 00000000000..f596feebd23
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-cart-checkout-motion-collapse
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Open and close the Add coupons panel in Cart and Checkout smoothly, so the content below moves instead of jumping.
diff --git a/plugins/woocommerce/client/blocks/assets/css/abstracts/_motion.scss b/plugins/woocommerce/client/blocks/assets/css/abstracts/_motion.scss
index 2eec0dc807c..ce9d3d2af3b 100644
--- a/plugins/woocommerce/client/blocks/assets/css/abstracts/_motion.scss
+++ b/plugins/woocommerce/client/blocks/assets/css/abstracts/_motion.scss
@@ -105,6 +105,30 @@ $wc-stagger-cap: 7;
 	}
 }

+// The timing for `animateCollapse` in base-utils. The space grows over `lg` and collapses over
+// `md`. The element always fades. With reduced motion, the space opens immediately, and closes after the fade.
+@mixin motion-collapse() {
+	$size: height, padding-top, padding-bottom, margin-top, margin-bottom;
+
+	&[data-wc-collapse] {
+		@include motion-transition($state: opacity, $move: $size, $easing: balanced);
+
+		@include motion-safe {
+			// Clip only the edge that moves, so that focus rings at the top and sides still show.
+			clip-path: inset(-100vw -100vw 0);
+		}
+	}
+
+	&[data-wc-collapse="out"] {
+		// Without the clip, content that loses its space covers the content below. Thus the space waits for the fade.
+		transition: motion-state(opacity), motion-hold($size...);
+
+		@include motion-safe {
+			transition: motion-move($size, md, balanced), motion-state(opacity);
+		}
+	}
+}
+
 // Sets --wc-motion-index on sibling rows. Rows after $wc-stagger-cap share the last index. `--wc-motion-index` is
 // registered as an integer in `assets/css/style.scss`, so `sibling-index()` counts the row, not the child that reads
 // it. Browsers without `sibling-index()` use `nth-child`. The `@supports` tests use a literal time, not `var()`.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/address-autocomplete/address-autocomplete.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/address-autocomplete/address-autocomplete.tsx
index d92625e9c31..3b9f64b432e 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/address-autocomplete/address-autocomplete.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/address-autocomplete/address-autocomplete.tsx
@@ -481,7 +481,7 @@ export const AddressAutocomplete = ( {
 	// The list stays mounted while it slides back to the field.
 	const presence = usePresence(
 		searchValue.length >= 3 && suggestions.length > 0 ? suggestions : null,
-		{ exit: ! isClosedByKey }
+		{ animate: ! isClosedByKey }
 	);

 	return (
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-presence.ts b/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-presence.ts
index 1fdeff7ea0c..4439556c79b 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-presence.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-presence.ts
@@ -2,17 +2,24 @@
  * External dependencies
  */
 import { act, renderHook } from '@testing-library/react';
+import { animateCollapse } from '@woocommerce/base-utils';

 /**
  * Internal dependencies
  */
 import { usePresence } from '../use-presence';

-type Props = { value: string[] | null; exit?: boolean };
+jest.mock( '@woocommerce/base-utils', () => ( {
+	...jest.requireActual( '@woocommerce/base-utils' ),
+	animateCollapse: jest.fn(),
+} ) );
+
+type Props = { value: string[] | null; animate?: boolean; collapse?: boolean };

 const renderUsePresence = ( initialProps: Props ) =>
 	renderHook(
-		( { value, exit = true }: Props ) => usePresence( value, { exit } ),
+		( { value, animate = true, collapse = false }: Props ) =>
+			usePresence( value, { animate, collapse } ),
 		{ initialProps }
 	);

@@ -83,23 +90,23 @@ describe( 'usePresence', () => {
 		expect( result.current.value ).toBe( reopened );
 	} );

-	it( 'removes the value immediately when exit is false', () => {
+	it( 'removes the value immediately when animate is false', () => {
 		const { result, rerender } = renderUsePresence( { value: open } );
 		result.current.ref.current = createAnimatingElement().element;

-		rerender( { value: null, exit: false } );
+		rerender( { value: null, animate: false } );
 		expect( result.current.value ).toBeNull();
 		expect( result.current.isExiting ).toBe( false );
 	} );

-	it( 'removes an exiting value when exit turns false', () => {
+	it( 'removes an exiting value when animate turns false', () => {
 		const { result, rerender } = renderUsePresence( { value: open } );
 		result.current.ref.current = createAnimatingElement().element;

 		rerender( { value: null } );
 		expect( result.current.isExiting ).toBe( true );

-		rerender( { value: null, exit: false } );
+		rerender( { value: null, animate: false } );
 		expect( result.current.value ).toBeNull();
 		expect( result.current.isExiting ).toBe( false );
 	} );
@@ -126,4 +133,76 @@ describe( 'usePresence', () => {
 		const { result } = renderHook( () => usePresence( NaN ) );
 		expect( result.current.value ).toBeNaN();
 	} );
+
+	describe( 'with collapse', () => {
+		beforeEach( () => jest.mocked( animateCollapse ).mockClear() );
+
+		it( 'does not grow a value that is there on the first render', () => {
+			renderUsePresence( { value: open, collapse: true } );
+			expect( animateCollapse ).not.toHaveBeenCalled();
+		} );
+
+		it( 'grows the element when a value arrives and collapses it when it goes', async () => {
+			const { result, rerender } = renderUsePresence( {
+				value: null,
+				collapse: true,
+			} );
+			const { element, finish } = createAnimatingElement();
+			result.current.ref.current = element;
+
+			rerender( { value: open, collapse: true } );
+			expect( animateCollapse ).toHaveBeenLastCalledWith(
+				element,
+				true,
+				true
+			);
+
+			rerender( { value: null, collapse: true } );
+			expect( animateCollapse ).toHaveBeenLastCalledWith(
+				element,
+				false
+			);
+			expect( result.current.isExiting ).toBe( true );
+
+			await act( async () => finish() );
+			expect( result.current.value ).toBeNull();
+		} );
+
+		it( 'stops the collapse without a grow when the value returns with animate false', () => {
+			const { result, rerender } = renderUsePresence( {
+				value: open,
+				collapse: true,
+			} );
+			const { element } = createAnimatingElement();
+			result.current.ref.current = element;
+
+			rerender( { value: null, collapse: true } );
+			rerender( { value: open, animate: false, collapse: true } );
+			expect( animateCollapse ).toHaveBeenLastCalledWith(
+				element,
+				true,
+				false
+			);
+			expect( result.current.isExiting ).toBe( false );
+		} );
+
+		it( 'stops a running grow when animate turns false', () => {
+			const { result, rerender } = renderUsePresence( {
+				value: null,
+				collapse: true,
+			} );
+			const { element } = createAnimatingElement();
+			result.current.ref.current = element;
+
+			rerender( { value: open, collapse: true } );
+			element.setAttribute( 'data-wc-collapse', 'in' );
+			jest.mocked( animateCollapse ).mockClear();
+			rerender( { value: open, animate: false, collapse: true } );
+			expect( animateCollapse ).toHaveBeenCalledWith(
+				element,
+				true,
+				false
+			);
+		} );
+	} );
 } );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-presence.ts b/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-presence.ts
index 8b41698d006..084ae7aff9d 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-presence.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-presence.ts
@@ -2,7 +2,7 @@
  * External dependencies
  */
 import { useLayoutEffect, useRef, useState } from '@wordpress/element';
-import { whenAnimationsEnd } from '@woocommerce/base-utils';
+import { animateCollapse, whenAnimationsEnd } from '@woocommerce/base-utils';

 /**
  * Keeps content mounted while it animates out, such as a dropdown that closes.
@@ -12,40 +12,65 @@ import { whenAnimationsEnd } from '@woocommerce/base-utils';
  * `isExiting` is unset again, so a transition turns around from its current position. Nothing is kept when nothing
  * animates, such as in Jest.
  *
- * @param value        The content to show, or `null` when there is none.
+ * @param value            The content to show, or `null` when there is none.
  * @param options
- * @param options.exit Set to `false` to remove the content immediately, for example after a key press.
+ * @param options.animate  Set to `false` to apply the change immediately, for example after a key press.
+ * @param options.collapse Set to `true` to grow `ref` when content arrives and collapse it when it goes.
+ *                         Content that is there on the first render does not grow.
  * @return The content to render, whether it is exiting, and the ref for the element that animates.
  */
-export function usePresence< T, E extends Element = HTMLDivElement >(
+export function usePresence< T, E extends HTMLElement = HTMLDivElement >(
 	value: T | null,
-	{ exit = true }: { exit?: boolean } = {}
+	{
+		animate = true,
+		collapse = false,
+	}: { animate?: boolean; collapse?: boolean } = {}
 ) {
 	const ref = useRef< E | null >( null );
 	// The state setters wrap the content, so that content that is a function is stored, not called.
 	const [ previousValue, setPreviousValue ] = useState( () => value );
 	const [ exitingValue, setExitingValue ] = useState< T | null >( null );
+	const isPresent = value !== null;
+	const wasPresentRef = useRef( isPresent );

-	// Adjust state while rendering, so the exiting content never unmounts for a frame. Turning `exit` off mid-exit
+	// Adjust state while rendering, so the exiting content never unmounts for a frame. Turning `animate` off mid-exit
 	// removes the content at once.
 	if (
 		! Object.is( value, previousValue ) ||
-		( ! exit && exitingValue !== null )
+		( ! animate && exitingValue !== null )
 	) {
 		setPreviousValue( () => value );
 		setExitingValue( () =>
-			value === null && exit ? previousValue : null
+			value === null && animate ? previousValue : null
 		);
 	}

+	// Grow before paint, so the content never shows at its full size first. This also turns around a collapse. Turning
+	// `animate` off mid-grow stops the grow at once.
+	useLayoutEffect( () => {
+		if (
+			collapse &&
+			isPresent &&
+			( ! wasPresentRef.current ||
+				( ! animate &&
+					ref.current?.hasAttribute( 'data-wc-collapse' ) ) )
+		) {
+			animateCollapse( ref.current, true, animate );
+		}
+		wasPresentRef.current = isPresent;
+	}, [ isPresent, collapse, animate ] );
+
 	// A layout effect runs after the exit style is in the DOM, so its transitions have started, and before paint, so
 	// content that does not animate is removed without a visible frame.
 	useLayoutEffect( () => {
 		if ( exitingValue === null ) {
 			return;
 		}
+		if ( collapse ) {
+			animateCollapse( ref.current, false );
+		}
 		return whenAnimationsEnd( ref.current, () => setExitingValue( null ) );
-	}, [ exitingValue ] );
+	}, [ exitingValue, collapse ] );

 	return {
 		value: value ?? exitingValue,
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/animate-collapse.ts b/plugins/woocommerce/client/blocks/assets/js/base/utils/animate-collapse.ts
new file mode 100644
index 00000000000..3f045bde883
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/animate-collapse.ts
@@ -0,0 +1,131 @@
+/**
+ * Internal dependencies
+ */
+import { whenAnimationsEnd } from './when-animations-end';
+
+// The `motion-collapse` mixin transitions the element while it has this attribute. The state is on the element, not
+// in the module, because each script bundle has its own copy of this module.
+const ATTRIBUTE = 'data-wc-collapse';
+
+// The properties that make the space, and the fade.
+const PROPERTIES = [
+	'height',
+	'paddingTop',
+	'paddingBottom',
+	'marginTop',
+	'marginBottom',
+	'opacity',
+] as const;
+
+type Values = Record< ( typeof PROPERTIES )[ number ], string >;
+
+const CLOSED: Values = {
+	height: '0px',
+	paddingTop: '0px',
+	paddingBottom: '0px',
+	marginTop: '0px',
+	marginBottom: '0px',
+	opacity: '0',
+};
+
+const readValues = ( element: HTMLElement ) => {
+	const style = getComputedStyle( element );
+	return Object.fromEntries(
+		PROPERTIES.map( ( property ) => [ property, style[ property ] ] )
+	) as Values;
+};
+
+/**
+ * Removes inline styles from an element, and the `style` attribute too when no styles are left, so that a motion
+ * leaves nothing behind.
+ *
+ * @param element    The element.
+ * @param properties The CSS property names to remove, such as `margin-bottom`.
+ */
+export const clearInlineStyle = (
+	element: HTMLElement,
+	...properties: string[]
+): void => {
+	properties.forEach( ( property ) =>
+		element.style.removeProperty( property )
+	);
+	if ( element.style.length === 0 ) {
+		// Chrome writes the cleared declarations back as `style=""` when nothing has read the attribute since.
+		element.getAttribute( 'style' );
+		element.removeAttribute( 'style' );
+	}
+};
+
+const reset = ( element: HTMLElement ) => {
+	element.removeAttribute( ATTRIBUTE );
+	PROPERTIES.forEach( ( property ) => {
+		element.style[ property ] = '';
+	} );
+	clearInlineStyle( element );
+};
+
+// Moves the element from `from`, or from its rest position, to open or closed.
+const move = ( element: HTMLElement, isOpen: boolean, from: Values | null ) => {
+	reset( element );
+	const open = readValues( element );
+	const start = from ?? ( isOpen ? CLOSED : open );
+	// Nothing to grow, such as when the content kept its size during the grow.
+	if (
+		isOpen &&
+		PROPERTIES.every(
+			( property ) => start[ property ] === open[ property ]
+		)
+	) {
+		return;
+	}
+
+	Object.assign( element.style, start );
+	// Apply the start values before the transitions exist, so that the transitions start from them.
+	element.getBoundingClientRect();
+	element.setAttribute( ATTRIBUTE, isOpen ? 'in' : 'out' );
+	Object.assign( element.style, isOpen ? open : CLOSED );
+
+	if ( isOpen ) {
+		whenAnimationsEnd( element, () => {
+			// A collapse that started later keeps its styles until the element unmounts. If the content changed size
+			// during the grow, the grow goes on from there to the new size, instead of jumping.
+			if ( element.getAttribute( ATTRIBUTE ) === 'in' ) {
+				move( element, true, readValues( element ) );
+			}
+		} );
+	}
+};
+
+/**
+ * Grows an element open or collapses it shut in the real layout, so the content below moves with it. The
+ * element also fades. Give the element the `motion-collapse` mixin, which sets the timing and the
+ * reduced motion rules. The element must not have its own inline styles for the properties that change.
+ *
+ * Call it before paint: after the element mounts to grow it, or when it starts to go to collapse it. If the element
+ * still moves, the motion turns around from its current position. If the content changes size while the element
+ * grows, the element grows on to the new size. A grown element has no inline styles when the motion ends. A collapsed
+ * element stays collapsed until it unmounts. Nothing changes when the browser has no Web Animations API, such as in
+ * Jest.
+ *
+ * @param element The element that grows or collapses.
+ * @param isOpen  Whether to grow the element (`true`) or collapse it (`false`).
+ * @param animate Set to `false` to stop the motion and show the element at its full size immediately.
+ */
+export const animateCollapse = (
+	element: HTMLElement | null,
+	isOpen: boolean,
+	animate = true
+): void => {
+	if ( typeof element?.getAnimations !== 'function' ) {
+		return;
+	}
+	// While the motion runs, the computed style is its current position.
+	const current = element.hasAttribute( ATTRIBUTE )
+		? readValues( element )
+		: null;
+	if ( ! animate ) {
+		reset( element );
+		return;
+	}
+	move( element, isOpen, current );
+};
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/index.js b/plugins/woocommerce/client/blocks/assets/js/base/utils/index.js
index b49bfdba340..3736468c64d 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/utils/index.js
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/index.js
@@ -19,3 +19,4 @@ export * from './pick';
 export * from './get-inline-styles';
 export * from './use-return-focus';
 export * from './when-animations-end';
+export * from './animate-collapse';
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/test/animate-collapse.ts b/plugins/woocommerce/client/blocks/assets/js/base/utils/test/animate-collapse.ts
new file mode 100644
index 00000000000..49f52209976
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/test/animate-collapse.ts
@@ -0,0 +1,176 @@
+/**
+ * Internal dependencies
+ */
+import { animateCollapse } from '../animate-collapse';
+
+const NATURAL: Record< string, string > = {
+	height: '40px',
+	paddingTop: '0px',
+	paddingBottom: '0px',
+	marginTop: '16px',
+	marginBottom: '0px',
+	opacity: '1',
+};
+
+// Jest has no layout, transitions, or Web Animations API. In the fake, the computed style is the inline style, or the
+// `natural` value when there is none. While `inProgress` has values and the element has the attribute of the helper,
+// a transition is at those values. Each time the helper sets its attribute, a new transition starts and replaces the
+// running one, as in a browser. `finish` ends the running transition.
+const createElement = () => {
+	const element = document.createElement( 'div' );
+	const inProgress: Record< string, string > = {};
+	const natural = { ...NATURAL };
+	let transition: {
+		playState: string;
+		finished: Promise< void >;
+		effect: { getComputedTiming: () => { endTime: number } };
+		end: () => void;
+		cancel: () => void;
+	} | null = null;
+	const startTransition = () => {
+		transition?.cancel();
+		let end = () => undefined as void;
+		let cancel = () => undefined as void;
+		const finished = new Promise< void >( ( resolve, reject ) => {
+			end = resolve;
+			cancel = reject;
+		} );
+		const next = {
+			playState: 'running',
+			finished,
+			effect: { getComputedTiming: () => ( { endTime: 300 } ) },
+			end: () => {
+				next.playState = 'finished';
+				end();
+			},
+			cancel: () => {
+				next.playState = 'idle';
+				cancel();
+			},
+		};
+		finished.catch( () => undefined );
+		transition = next;
+	};
+	const setAttribute = element.setAttribute.bind( element );
+	element.setAttribute = ( name: string, value: string ) => {
+		setAttribute( name, value );
+		if ( name === 'data-wc-collapse' ) {
+			startTransition();
+		}
+	};
+	element.getAnimations = () =>
+		element.hasAttribute( 'data-wc-collapse' ) &&
+		transition?.playState === 'running'
+			? [ transition as unknown as Animation ]
+			: [];
+	jest.spyOn( window, 'getComputedStyle' ).mockImplementation(
+		() =>
+			new Proxy( {} as CSSStyleDeclaration, {
+				get: ( _, property: string ) =>
+					( element.hasAttribute( 'data-wc-collapse' ) &&
+						inProgress[ property ] ) ||
+					( element.style as unknown as Record< string, string > )[
+						property
+					] ||
+					natural[ property ],
+			} )
+	);
+	const finish = async () => {
+		transition?.end();
+		await new Promise( ( resolve ) => setTimeout( resolve ) );
+	};
+	return { element, inProgress, natural, finish };
+};
+
+describe( 'animateCollapse', () => {
+	afterEach( () => jest.restoreAllMocks() );
+
+	it( 'does nothing when the browser has no Web Animations API', () => {
+		const element = document.createElement( 'div' );
+		animateCollapse( element, true );
+		animateCollapse( null, false );
+		expect( element.getAttributeNames() ).toEqual( [] );
+	} );
+
+	it( 'grows the space and the opacity from nothing to the natural values', () => {
+		const { element } = createElement();
+		const setProperty = jest.spyOn( element.style, 'height', 'set' );
+		animateCollapse( element, true );
+
+		expect( setProperty.mock.calls ).toEqual( [
+			[ '' ],
+			[ '0px' ],
+			[ '40px' ],
+		] );
+		expect( element.style.marginTop ).toBe( '16px' );
+		expect( element.style.opacity ).toBe( '1' );
+		expect( element.getAttribute( 'data-wc-collapse' ) ).toBe( 'in' );
+	} );
+
+	it( 'leaves nothing behind when the grow ends', async () => {
+		const { element, finish } = createElement();
+		animateCollapse( element, true );
+
+		await finish();
+		expect( element.getAttributeNames() ).toEqual( [] );
+	} );
+
+	it( 'grows on to the new size when the content changes size during the grow', async () => {
+		const { element, natural, finish } = createElement();
+		const setHeight = jest.spyOn( element.style, 'height', 'set' );
+		animateCollapse( element, true );
+		natural.height = '80px';
+		setHeight.mockClear();
+
+		await finish();
+		expect( setHeight.mock.calls ).toEqual( [
+			[ '' ],
+			[ '40px' ],
+			[ '80px' ],
+		] );
+		expect( element.style.height ).toBe( '80px' );
+		expect( element.getAttribute( 'data-wc-collapse' ) ).toBe( 'in' );
+
+		await finish();
+		expect( element.getAttributeNames() ).toEqual( [] );
+	} );
+
+	it( 'collapses to nothing and stays collapsed when the collapse ends', async () => {
+		const { element, finish } = createElement();
+		animateCollapse( element, false );
+		expect( element.getAttribute( 'data-wc-collapse' ) ).toBe( 'out' );
+
+		await finish();
+		expect( element.style.height ).toBe( '0px' );
+		expect( element.style.marginTop ).toBe( '0px' );
+		expect( element.style.opacity ).toBe( '0' );
+	} );
+
+	it( 'turns around from the current position', async () => {
+		const { element, inProgress, finish } = createElement();
+		const setHeight = jest.spyOn( element.style, 'height', 'set' );
+		animateCollapse( element, true );
+		Object.assign( inProgress, { height: '10px', marginTop: '4px' } );
+		setHeight.mockClear();
+
+		animateCollapse( element, false );
+		expect( setHeight.mock.calls ).toEqual( [
+			[ '' ],
+			[ '10px' ],
+			[ '0px' ],
+		] );
+		expect( element.getAttribute( 'data-wc-collapse' ) ).toBe( 'out' );
+
+		// The end of the grow must not remove the styles of the collapse.
+		await finish();
+		expect( element.style.height ).toBe( '0px' );
+	} );
+
+	it( 'removes the motion and its styles when animate is false', () => {
+		const { element } = createElement();
+		animateCollapse( element, false );
+
+		animateCollapse( element, true, false );
+		expect( element.getAttributeNames() ).toEqual( [] );
+	} );
+} );
diff --git a/plugins/woocommerce/client/blocks/docs/contributors/motion.md b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
index 5a2600994d5..d8fdad2ed42 100644
--- a/plugins/woocommerce/client/blocks/docs/contributors/motion.md
+++ b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
@@ -80,6 +80,7 @@ Use the helpers in `assets/css/abstracts/_motion.scss`. Do not write `transition
 | `@include motion-stagger( $keyframes )` | Sibling rows that enter 50ms apart. It counts rows with `sibling-index()`, and with `nth-child` in browsers that do not have it. | `@include motion-stagger;` |
 | `@include motion-fade-in` / `motion-fade-out` | A fade with no movement. | |
 | `@include motion-dim( $states )` | Dims the element while `$states` matches, such as `".is-disabled"`. | Cart rows, disabled radios |
+| `@include motion-collapse` | The timing for `animateCollapse`. The content grows over 300ms and collapses over 200ms, and fades. With reduced motion, it only fades. | `Panel` content |
 | `@include motion-safe { … }` | Movement that the other helpers do not cover. | |

 `assets/css/style.scss` has the shared keyframes. `wc-fade-in` and `wc-fade-out` only fade. `wc-rise`, `wc-grow`, and `wc-shrink` move with `translate`, `scale`, and `filter`, so they combine with a fade and with the resting `transform` of an element.
@@ -91,7 +92,8 @@ Motion that changes the layout runs in JavaScript, because it must measure sizes
 | Helper | Use |
 |--------|-----|
 | `whenAnimationsEnd( element, callback )` (`@woocommerce/base-utils`) | Runs `callback` when the animations of `element` end, instead of after a fixed timeout. It waits again if a transition turns around. It returns a function that cancels the callback. |
-| `usePresence( value, { exit } )` (`@woocommerce/base-hooks`) | Keeps content mounted while it animates out. Pass the content, or `null` to remove it. It returns `{ value, isExiting, ref }`. Put `ref` on the element that animates. Pass `exit: false` to remove the content immediately, for example after a key press. |
+| `usePresence( value, { animate, collapse } )` (`@woocommerce/base-hooks`) | Keeps content mounted while it animates out. Pass the content, or `null` to remove it. It returns `{ value, isExiting, ref }`. Put `ref` on the element that animates. Pass `collapse: true` to grow and collapse `ref` in the real layout. Pass `animate: false` to apply the change immediately, for example after a key press. |
+| `animateCollapse( element, isOpen, animate )` (`@woocommerce/base-utils`) | Grows `element` open or collapses it shut in the real layout, and turns around if it still moves. Give `element` the `motion-collapse` mixin. Use it through `usePresence`. |

 ## Techniques

diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/index.tsx b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/index.tsx
index 6de6fd07a4a..e938d8b862c 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/index.tsx
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/index.tsx
@@ -1,12 +1,13 @@
 /**
  * External dependencies
  */
-import { useState } from '@wordpress/element';
+import { useRef, useState } from '@wordpress/element';
 import clsx from 'clsx';
 import { Icon, chevronUp, chevronDown } from '@wordpress/icons';
 import type { ReactNode, ReactElement } from 'react';
 import { Button } from '@ariakit/react';
 import deprecated from '@wordpress/deprecated';
+import { exitingProps, usePresence } from '@woocommerce/base-hooks';
 /**
  * Internal dependencies
  */
@@ -49,6 +50,12 @@ const Panel = ( {
 		} );
 	}

+	// The open state that the last key press on the button set. A key press applies immediately.
+	const keyStateRef = useRef< boolean | null >( null );
+	const animate = keyStateRef.current !== isOpen;
+	// The content grows and collapses, so the content below moves with it.
+	const content = usePresence( isOpen || null, { animate, collapse: true } );
+
 	return (
 		<div
 			role={ headingLevel ? 'heading' : undefined }
@@ -60,8 +67,15 @@ const Panel = ( {
 			<Button
 				render={ <div /> }
 				aria-expanded={ isOpen }
+				// Stops the gap under the button from animating after a key press. Set in the same render as
+				// `aria-expanded`, so the browser sees both together.
+				{ ...( ! animate && { 'data-wc-instant': '' } ) }
 				className="wc-block-components-panel__button"
-				onClick={ () => setIsOpen( ! isOpen ) }
+				onClick={ ( event ) => {
+					// A click that a key press starts has no click count.
+					keyStateRef.current = event.detail === 0 ? ! isOpen : null;
+					setIsOpen( ! isOpen );
+				} }
 			>
 				<Icon
 					aria-hidden="true"
@@ -70,8 +84,12 @@ const Panel = ( {
 				/>
 				{ title }
 			</Button>
-			{ isOpen && (
-				<div className="wc-block-components-panel__content">
+			{ content.value && (
+				<div
+					ref={ content.ref }
+					className="wc-block-components-panel__content"
+					{ ...exitingProps( content.isExiting ) }
+				>
 					{ children }
 				</div>
 			) }
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/style.scss b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/style.scss
index 22d1974b10c..4bcd1252a66 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/style.scss
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/panel/style.scss
@@ -51,3 +51,25 @@
 		display: none;
 	}
 }
+
+// Only the blocks that use motion animate the panel.
+:where(.wp-block-woocommerce-cart, .wp-block-woocommerce-checkout) {
+	// The gap under the button opens and closes with the content, at the same speed.
+	.wc-block-components-panel__button {
+		@include motion-transition($move: margin-bottom, $easing: balanced);
+
+		&[aria-expanded="false"] {
+			transition: motion-hold(margin-bottom);
+			@include motion-transition($move: margin-bottom, $duration: md, $easing: balanced);
+		}
+
+		// A key press applies immediately, as the content does.
+		&[data-wc-instant] {
+			transition: none;
+		}
+	}
+
+	.wc-block-components-panel__content {
+		@include motion-collapse;
+	}
+}