Commit 4348c303425 for woocommerce

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

    Add motion to Checkout sections and the mobile order summary (#70930)

    * Add motion to Checkout sections and the mobile order summary

    * Use a logical property for the order note margin

    * Remove pending payment collapse copies on keyboard changes

    Clicking A then B left an empty copy collapsing in A. Pressing an arrow key to C before it ended only applied C at once, so A's space kept collapsing. Instant changes now remove every pending copy in the accordion.

    * Skip empty collapse placeholders under reduced motion

    An empty box only exists to collapse the space. Under reduced motion it held its height until the fade ended, so content below moved down then back up.

    * Use the shared exiting attributes in the Checkout order summary

    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-checkout-sections b/plugins/woocommerce/changelog/add-cart-checkout-motion-checkout-sections
new file mode 100644
index 00000000000..ae40316a0c8
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-cart-checkout-motion-checkout-sections
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Checkout: the account password, order note, payment method fields, and mobile order summary now grow open and collapse shut smoothly when shoppers show or hide them.
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
index cb6b0d58018..bafa5c282d3 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/utils/animate-collapse.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/animate-collapse.ts
@@ -188,18 +188,48 @@ export const inertCopy = ( element: HTMLElement ): HTMLElement => {
 	return copy;
 };

+// An empty, inert box with the size of `element`. It counts as moving, so `animateCollapse` starts from that size.
+const emptyBox = ( element: HTMLElement ): HTMLElement => {
+	const box = document.createElement( 'div' );
+	Object.assign( box.style, readValues( element ), {
+		boxSizing: getComputedStyle( element ).boxSizing,
+		borderStyle: 'solid',
+		borderColor: 'transparent',
+	} );
+	box.setAttribute( ATTRIBUTE, 'out' );
+	box.setAttribute( 'inert', '' );
+	box.setAttribute( 'aria-hidden', 'true' );
+	return box;
+};
+
 /**
  * Collapses an inert copy of an element in its place, so that the element itself can unmount at once. Use it for a
  * form that goes, so that its fields stop counting immediately. The copy has no `id`, `name`, or `for` attributes, and
  * it is removed when the collapse ends. Call it just before the element unmounts, while it is still in the page.
  *
- * @param element The element that unmounts.
+ * With `empty`, the copy is an empty box of the same size, so the content disappears at once and only its space
+ * collapses. Use it for content that other scripts own, such as payment fields: their scripts can find a full copy,
+ * and copied custom elements run their own code.
+ *
+ * @param element       The element that unmounts.
+ * @param options
+ * @param options.empty Collapse an empty box instead of a copy of the content.
  */
-export const collapseCopy = ( element: HTMLElement | null ): void => {
+export const collapseCopy = (
+	element: HTMLElement | null,
+	{ empty = false }: { empty?: boolean } = {}
+): void => {
 	if ( typeof element?.getAnimations !== 'function' ) {
 		return;
 	}
-	const copy = inertCopy( element );
+	// Under reduced motion the space changes at once, so an empty box has nothing to show.
+	if (
+		empty &&
+		window.matchMedia?.( '(prefers-reduced-motion: reduce)' ).matches
+	) {
+		return;
+	}
+	const copy = empty ? emptyBox( element ) : inertCopy( element );
 	copy.setAttribute( COPY, element.className );
 	// A motion that runs continues from its current position.
 	if ( element.hasAttribute( ATTRIBUTE ) ) {
@@ -209,3 +239,15 @@ export const collapseCopy = ( element: HTMLElement | null ): void => {
 	animateCollapse( copy, false );
 	whenAnimationsEnd( copy, () => copy.remove() );
 };
+
+/**
+ * Removes every copy that `collapseCopy` still collapses inside a container, so that a change that applies
+ * immediately leaves no space behind.
+ *
+ * @param container The element that holds the copies.
+ */
+export const removeCollapseCopies = ( container: HTMLElement | null ): void => {
+	container
+		?.querySelectorAll( `[${ COPY }]` )
+		.forEach( ( copy ) => copy.remove() );
+};
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
index 27cd704810a..b695e5a8dcf 100644
--- 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
@@ -1,7 +1,11 @@
 /**
  * Internal dependencies
  */
-import { animateCollapse, collapseCopy } from '../animate-collapse';
+import {
+	animateCollapse,
+	collapseCopy,
+	removeCollapseCopies,
+} from '../animate-collapse';

 const NATURAL: Record< string, string > = {
 	height: '40px',
@@ -343,4 +347,46 @@ describe( 'collapseCopy', () => {
 			[ '40px' ],
 		] );
 	} );
+
+	it( 'leaves no empty box under reduced motion, but still copies content', () => {
+		window.matchMedia = jest.fn().mockReturnValue( { matches: true } );
+		const { element, parent } = createForm();
+		collapseCopy( element, { empty: true } );
+		expect( parent.children ).toHaveLength( 2 );
+
+		collapseCopy( element );
+		expect( parent.children ).toHaveLength( 3 );
+		// @ts-expect-error The mock is not part of jsdom.
+		delete window.matchMedia;
+	} );
+} );
+
+describe( 'removeCollapseCopies', () => {
+	afterEach( () => {
+		jest.restoreAllMocks();
+		document.body.innerHTML = '';
+		// @ts-expect-error The fake is not part of jsdom.
+		delete HTMLElement.prototype.getAnimations;
+	} );
+
+	it( 'removes every copy that still collapses inside the container', () => {
+		const { element: first } = createElement();
+		const { element: second } = createElement();
+		const firstOption = document.createElement( 'div' );
+		const secondOption = document.createElement( 'div' );
+		firstOption.append( first );
+		secondOption.append( second );
+		const container = document.createElement( 'div' );
+		container.append( firstOption, secondOption );
+		document.body.append( container );
+
+		collapseCopy( first, { empty: true } );
+		collapseCopy( second, { empty: true } );
+		first.remove();
+		second.remove();
+		expect( container.querySelectorAll( '[inert]' ) ).toHaveLength( 2 );
+
+		removeCollapseCopies( container );
+		expect( container.querySelectorAll( '[inert]' ) ).toHaveLength( 0 );
+	} );
 } );
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/cart-checkout-shared/payment-methods/style.scss b/plugins/woocommerce/client/blocks/assets/js/blocks/cart-checkout-shared/payment-methods/style.scss
index 7ad03d7bec5..0351b6d46b2 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/cart-checkout-shared/payment-methods/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/cart-checkout-shared/payment-methods/style.scss
@@ -81,3 +81,15 @@
 		display: none;
 	}
 }
+
+// The fields of the selected payment method grow in, and the space of the fields of the last one collapses, as an empty
+// box at the same timing, so the content below moves one way. `flow-root` keeps a first child's top margin, such as a
+// gateway's `<p>`, inside the content, so that it collapses with it.
+:where(.wp-block-woocommerce-checkout) .wc-block-components-radio-control-accordion-content {
+	display: flow-root;
+	@include motion-collapse;
+}
+
+:where(.wp-block-woocommerce-checkout) .wc-block-components-radio-control-accordion-option > [data-wc-collapse-copy] {
+	@include motion-collapse($out: lg);
+}
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-contact-information-block/block.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-contact-information-block/block.tsx
index 8c146e5602e..cb1d18a2a59 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-contact-information-block/block.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-contact-information-block/block.tsx
@@ -16,6 +16,7 @@ import { useDispatch, useSelect } from '@wordpress/data';
 import { checkoutStore } from '@woocommerce/block-data';
 import { CONTACT_FORM_KEYS } from '@woocommerce/block-settings';
 import { Form } from '@woocommerce/base-components/cart-checkout';
+import { useToggleCollapse } from '@woocommerce/base-hooks';

 /**
  * Internal dependencies
@@ -44,6 +45,13 @@ const CreateAccountUI = (): React.ReactElement | null => {
 		: ( showCreateAccountCheckbox && shouldCreateAccount ) ||
 			! allowGuestCheckout;

+	// The checkbox grows the password field in and collapses it out.
+	const passwordCollapse = useToggleCollapse( showCreateAccountPassword, () =>
+		document.querySelector< HTMLElement >(
+			'.wc-block-components-address-form__password:not([data-wc-collapse-copy])'
+		)
+	);
+
 	if (
 		! allowGuestCheckout &&
 		! showCreateAccountCheckbox &&
@@ -67,6 +75,7 @@ const CreateAccountUI = (): React.ReactElement | null => {
 			) }
 			{ showCreateAccountCheckbox && (
 				<CheckboxControl
+					ref={ passwordCollapse.triggerRef }
 					className="wc-block-checkout__create-account"
 					label={ sprintf(
 						/* translators: Store name */
@@ -75,6 +84,7 @@ const CreateAccountUI = (): React.ReactElement | null => {
 					) }
 					checked={ shouldCreateAccount }
 					onChange={ ( value ) => {
+						passwordCollapse.onToggle();
 						void __internalSetShouldCreateAccount( value );
 						void __internalSetCustomerPassword( '' );
 					} }
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-fields-block/style.scss b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-fields-block/style.scss
index beff00a416f..885783f52fb 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-fields-block/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-fields-block/style.scss
@@ -99,10 +99,12 @@
 	}
 }

-// The billing section and the address line 2 field grow in, and the billing section collapses out.
+// The billing section, the address line 2 field, and the account password grow in, and the ones that a checkbox
+// removes collapse out.
 :where(.wp-block-woocommerce-checkout) {
 	.wc-block-checkout__billing-fields,
-	.wc-block-components-address-form__address_2 {
+	.wc-block-components-address-form__address_2,
+	.wc-block-components-address-form__password {
 		@include motion-collapse;
 	}

diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/frontend.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/frontend.tsx
index 36d2ed63704..b937d85b947 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/frontend.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/frontend.tsx
@@ -1,9 +1,11 @@
 /**
  * External dependencies
  */
+import { exitingProps } from '@woocommerce/base-hooks';
 import { TotalsFooterItem } from '@woocommerce/base-components/cart-checkout';
 import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
 import { useStoreCart } from '@woocommerce/base-context/hooks';
+import { animateCollapse, whenAnimationsEnd } from '@woocommerce/base-utils';
 import { __ } from '@wordpress/i18n';
 import { Icon, chevronDown, chevronUp } from '@wordpress/icons';
 import {
@@ -32,6 +34,7 @@ const FrontendBlock = ( {
 	const { cartTotals } = useStoreCart();
 	const {
 		isOpen,
+		isClickToggle,
 		hasContainerWidth,
 		isLarge,
 		closeSummary,
@@ -61,7 +64,21 @@ const FrontendBlock = ( {

 	const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
 	const totalPrice = parseInt( cartTotals.total_price, 10 );
-	const showInline = ! hasContainerWidth || isLarge || isOpen;
+	const isToggleShown = hasContainerWidth && ! isLarge;
+
+	// After a tap, the content collapses inline before it moves to the checkout actions. Closing because the shopper
+	// scrolled past the summary applies immediately, as its scroll correction expects. So does a resize that hides
+	// the toggle.
+	const [ isClosing, setIsClosing ] = useState( false );
+	const [ previousIsOpen, setPreviousIsOpen ] = useState( isOpen );
+	if ( isOpen !== previousIsOpen ) {
+		setPreviousIsOpen( isOpen );
+		setIsClosing( ! isOpen && isClickToggle && isToggleShown );
+	}
+	if ( isClosing && ! isToggleShown ) {
+		setIsClosing( false );
+	}
+	const showInline = ! isToggleShown || isOpen || isClosing;

 	useEffect( () => {
 		if (
@@ -140,6 +157,27 @@ const FrontendBlock = ( {
 		showInline,
 	] );

+	// Runs after the effect above has moved the content in or out. A tap grows the content open, or collapses it, and
+	// turns around if the motion still runs. Any other change applies immediately and leaves no collapse behind, such
+	// as a resize in the middle of the motion.
+	const wasOpenRef = useRef( isOpen );
+	useLayoutEffect( () => {
+		const wasOpen = wasOpenRef.current;
+		wasOpenRef.current = isOpen;
+		if ( ! inlineHost ) {
+			return;
+		}
+		if ( isClosing ) {
+			animateCollapse( inlineHost, false );
+			return whenAnimationsEnd( inlineHost, () => setIsClosing( false ) );
+		}
+		animateCollapse(
+			inlineHost,
+			true,
+			isOpen && ! wasOpen && isClickToggle && isToggleShown
+		);
+	}, [ inlineHost, isClosing, isOpen, isClickToggle, isToggleShown ] );
+
 	useLayoutEffect( () => {
 		return () => contentContainer.remove();
 	}, [ contentContainer ] );
@@ -178,10 +216,11 @@ const FrontendBlock = ( {
 					className={ clsx(
 						'wc-block-components-checkout-order-summary__content',
 						{
-							'is-open': isOpen,
+							'is-open': isOpen || isClosing,
 						}
 					) }
 					id={ ariaControlsId }
+					{ ...exitingProps( isClosing ) }
 				/>
 			</div>
 			<CheckoutOrderSummaryFill>
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/style.scss b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/style.scss
index 260f65aca61..a966af12bd0 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/style.scss
@@ -128,6 +128,8 @@

 		.wc-block-components-checkout-order-summary__content {
 			display: none;
+			// A tap on the title grows the content open and collapses it shut.
+			@include motion-collapse;

 			&.is-open {
 				border-bottom: 1px solid $universal-border-light;
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/test/collapsible-bar.js b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/test/collapsible-bar.js
index 25f7b9c5f07..2d74beb1806 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/test/collapsible-bar.js
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/test/collapsible-bar.js
@@ -408,4 +408,86 @@ describe( 'Checkout Order Summary placement', () => {
 			orderExtension
 		);
 	} );
+
+	describe( 'motion', () => {
+		// Jest has no transitions. In the fake, an element runs one transition while it has the attribute of
+		// `animateCollapse`, until `finish` ends it.
+		let finish;
+		beforeEach( () => {
+			let isRunning = true;
+			let resolveFinished;
+			const transition = {
+				playState: 'running',
+				finished: new Promise( ( resolve ) => {
+					resolveFinished = resolve;
+				} ),
+				effect: { getComputedTiming: () => ( { endTime: 200 } ) },
+			};
+			HTMLElement.prototype.getAnimations = function () {
+				return isRunning && this.hasAttribute( 'data-wc-collapse' )
+					? [ transition ]
+					: [];
+			};
+			finish = async () => {
+				isRunning = false;
+				await act( async () => resolveFinished() );
+			};
+		} );
+
+		afterEach( () => {
+			delete HTMLElement.prototype.getAnimations;
+		} );
+
+		it( 'keeps tapped content inline and inert while it collapses, then moves it and leaves nothing behind', async () => {
+			const { container } = renderWithSlot( 'is-medium' );
+			const title = screen.getByRole( 'button', {
+				name: /Order summary/,
+			} );
+			const inlineSummary = container.querySelector(
+				'.wc-block-components-checkout-order-summary__content'
+			);
+			const summaryContent = screen.getByTestId( 'summary-content' );
+
+			fireEvent.click( title, { detail: 1 } );
+			expect( inlineSummary ).toHaveAttribute( 'data-wc-collapse', 'in' );
+
+			fireEvent.click( title, { detail: 1 } );
+			expect( title ).toHaveAttribute( 'aria-expanded', 'false' );
+			expect( inlineSummary ).toContainElement( summaryContent );
+			expect( inlineSummary ).toHaveClass( 'is-open' );
+			expect( inlineSummary ).toHaveAttribute( 'inert' );
+			expect( inlineSummary ).toHaveAttribute(
+				'data-wc-collapse',
+				'out'
+			);
+
+			await finish();
+			expect(
+				container.querySelector( '.checkout-order-summary-block-fill' )
+			).toContainElement( summaryContent );
+			expect( inlineSummary ).not.toHaveClass( 'is-open' );
+			expect( inlineSummary ).not.toHaveAttribute( 'inert' );
+			expect( inlineSummary ).not.toHaveAttribute( 'data-wc-collapse' );
+			expect( inlineSummary ).not.toHaveAttribute( 'style' );
+		} );
+
+		it( 'applies a key press immediately', () => {
+			const { container } = renderWithSlot( 'is-medium' );
+			const title = screen.getByRole( 'button', {
+				name: /Order summary/,
+			} );
+			const inlineSummary = container.querySelector(
+				'.wc-block-components-checkout-order-summary__content'
+			);
+
+			fireEvent.keyDown( title, { key: 'Enter' } );
+			expect( inlineSummary ).not.toHaveAttribute( 'data-wc-collapse' );
+
+			fireEvent.keyDown( title, { key: 'Enter' } );
+			expect(
+				container.querySelector( '.checkout-order-summary-block-fill' )
+			).toContainElement( screen.getByTestId( 'summary-content' ) );
+			expect( inlineSummary ).not.toHaveAttribute( 'inert' );
+		} );
+	} );
 } );
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/use-order-summary-toggle.ts b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/use-order-summary-toggle.ts
index 96985d234a6..d8017c7215e 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/use-order-summary-toggle.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-order-summary-block/use-order-summary-toggle.ts
@@ -3,10 +3,12 @@
  */
 import { useContainerWidthContext } from '@woocommerce/base-context';
 import { useCallback, useId, useState } from '@wordpress/element';
-import type { HTMLAttributes, KeyboardEvent } from 'react';
+import type { HTMLAttributes, KeyboardEvent, MouseEvent } from 'react';

 export type OrderSummaryToggle = {
 	isOpen: boolean;
+	// Whether a click or tap made the last change of `isOpen`. Key presses and closing in code apply immediately.
+	isClickToggle: boolean;
 	hasContainerWidth: boolean;
 	isLarge: boolean;
 	closeSummary: () => void;
@@ -29,14 +31,25 @@ export type OrderSummaryToggle = {
  */
 export const useOrderSummaryToggle = (): OrderSummaryToggle => {
 	const { hasContainerWidth, isLarge } = useContainerWidthContext();
-	const [ isOpen, setIsOpen ] = useState( false );
+	const [ { isOpen, isClickToggle }, setToggle ] = useState( {
+		isOpen: false,
+		isClickToggle: false,
+	} );
 	const ariaControlsId = useId();
-	const closeSummary = useCallback( () => setIsOpen( false ), [] );
+	const closeSummary = useCallback(
+		() => setToggle( { isOpen: false, isClickToggle: false } ),
+		[]
+	);

 	const toggleProps = ! isLarge
 		? {
 				role: 'button',
-				onClick: () => setIsOpen( ! isOpen ),
+				// A click that a key press or assistive technology starts has no click count.
+				onClick: ( event: MouseEvent ) =>
+					setToggle( {
+						isOpen: ! isOpen,
+						isClickToggle: event.detail !== 0,
+					} ),
 				'aria-expanded': isOpen,
 				'aria-controls': ariaControlsId,
 				tabIndex: 0,
@@ -46,7 +59,7 @@ export const useOrderSummaryToggle = (): OrderSummaryToggle => {
 						// surrounding checkout form. A real button would
 						// suppress both for us.
 						event.preventDefault();
-						setIsOpen( ! isOpen );
+						setToggle( { isOpen: ! isOpen, isClickToggle: false } );
 					}
 				},
 			}
@@ -54,6 +67,7 @@ export const useOrderSummaryToggle = (): OrderSummaryToggle => {

 	return {
 		isOpen,
+		isClickToggle,
 		hasContainerWidth,
 		isLarge,
 		closeSummary,
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/index.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/index.tsx
index f61c04998c8..b6f1fc6a7bf 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/index.tsx
@@ -2,8 +2,9 @@
  * External dependencies
  */
 import { __ } from '@wordpress/i18n';
-import { useState } from '@wordpress/element';
+import { useRef, useState } from '@wordpress/element';
 import { CheckboxControl, Textarea } from '@woocommerce/blocks-components';
+import { useToggleCollapse } from '@woocommerce/base-hooks';

 /**
  * Internal dependencies
@@ -28,14 +29,25 @@ const CheckoutOrderNotes = ( {
 	// text entered previously by the user when the checkbox is re-enabled
 	// while keeping the context clean if the checkbox is disabled.
 	const [ hiddenOrderNotesText, setHiddenOrderNotesText ] = useState( '' );
+	const containerRef = useRef< HTMLDivElement >( null );
+	// The checkbox grows the note in and collapses it out.
+	const noteCollapse = useToggleCollapse(
+		withOrderNotes,
+		() =>
+			containerRef.current?.querySelector< HTMLElement >(
+				':scope > .wc-block-components-textarea:not([data-wc-collapse-copy])'
+			) ?? null
+	);

 	return (
-		<div className="wc-block-checkout__add-note">
+		<div className="wc-block-checkout__add-note" ref={ containerRef }>
 			<CheckboxControl
+				ref={ noteCollapse.triggerRef }
 				disabled={ disabled }
 				label={ __( 'Add a note to your order', 'woocommerce' ) }
 				checked={ withOrderNotes }
 				onChange={ ( isChecked ) => {
+					noteCollapse.onToggle();
 					setWithOrderNotes( isChecked );
 					if ( isChecked ) {
 						// When re-enabling the checkbox, store in context the
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/style.scss b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/style.scss
index c7a2dd6ec9b..1ecbcee92f2 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/order-notes/style.scss
@@ -1,5 +1,14 @@
 .wc-block-checkout__add-note {
 	display: flex;
 	flex-direction: column;
-	gap: $gap;
+
+	// A margin, not a gap, so that the space closes with the note when it collapses.
+	> .wc-block-components-textarea {
+		margin-block-start: $gap;
+	}
+}
+
+// The note grows in and collapses out with its checkbox.
+:where(.wp-block-woocommerce-checkout) .wc-block-checkout__add-note > .wc-block-components-textarea {
+	@include motion-collapse;
 }
diff --git a/plugins/woocommerce/client/blocks/docs/contributors/motion.md b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
index 4465f1a6dc3..ef4e856d5c9 100644
--- a/plugins/woocommerce/client/blocks/docs/contributors/motion.md
+++ b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
@@ -96,7 +96,7 @@ Motion that changes the layout runs in JavaScript, because it must measure sizes
 | `useListEntrance( ref )` (`@woocommerce/base-hooks`) | Lets the items of a list stagger in once. Call the function it returns when the items first show, such as from the `onShow` of `DelayedContentWithSkeleton`. It sets `data-wc-list-entering` on `ref` until the entrances end. Style the items with `motion-stagger` under that attribute. |
 | `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, from )` (`@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` when the component owns the content. Pass `from`, such as `{ height: '20px' }`, to grow from the size of the content that `element` replaces, or to change the height of an element that stays. |
-| `collapseCopy( element )` (`@woocommerce/base-utils`) | Collapses an inert copy of `element` in its place, so that `element` can unmount at once. Call it just before `element` unmounts. If `element` grows again first, it grows from the copy. |
+| `collapseCopy( element, { empty } )` (`@woocommerce/base-utils`) | Collapses an inert copy of `element` in its place, so that `element` can unmount at once. Call it just before `element` unmounts. If `element` grows again first, it grows from the copy. The copy has no `id`, `name`, or `for` attributes. Pass `empty: true` for content that other scripts own, such as payment fields: the content disappears at once, and only an empty box of its size collapses. |
 | `useToggleCollapse( isShown, getElement, { growFromTrigger } )` (`@woocommerce/base-hooks`) | Content that a control shows and hides, such as a checkbox that reveals a field. Call the `onToggle` that it returns in the handler of the control, before the state changes. Pass it the click event if there is one, or else put `triggerRef` on the control. `getElement` must not return the copy, which keeps the element's classes: find the element by id, or skip `[data-wc-collapse-copy]`. After a click, the element grows in, or an inert copy of it collapses while the real element unmounts. After a key press, the change applies immediately. Pass `growFromTrigger: true` when the content replaces the control, to grow from the height of the control. |
 | `captureSwap( container, direction )` and `playSwap( snapshot )` (`@woocommerce/base-utils`) | Swap the group of sections that a choice changes as one movement. Call `captureSwap` in the event handler, before the change, with the way that the selection moved on the screen (1 to the right, -1 to the left). Call `playSwap` in a layout effect after the sections change. Inert copies of the old sections fade out, the sections after the group hold their place until the copies have gone, and then everything moves one time. A new swap continues from the current position. |
 | `useOrderSummaryRow( cart, isShown )` (`@woocommerce/base-context/hooks`) | An order summary row that only shows sometimes, such as Fees. The row appears and goes when the skeletons end, and grows and collapses through `usePresence`. Rows of the cart that loads with the page show immediately. It returns `{ cart, isStale, wrapperProps }`. Render the row from `cart` while it is not `null`, and spread `wrapperProps` on its `TotalsWrapper`. `isStale` is true while `cart` is not the current cart, so disable controls in the row then. |
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/radio-control-accordion/index.tsx b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/radio-control-accordion/index.tsx
index b0fa3ac1280..a17e10e45b8 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/radio-control-accordion/index.tsx
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/radio-control-accordion/index.tsx
@@ -3,7 +3,12 @@
  */
 import clsx from 'clsx';
 import { withInstanceId } from '@wordpress/compose';
-import { useMemo } from '@wordpress/element';
+import { useLayoutEffect, useMemo, useRef } from '@wordpress/element';
+import {
+	animateCollapse,
+	collapseCopy,
+	removeCollapseCopies,
+} from '@woocommerce/base-utils';

 /**
  * Internal dependencies
@@ -42,11 +47,27 @@ const RadioControlAccordion = ( {
 		return options.findIndex( ( option ) => option.value === selected );
 	}, [ options, selected ] );

+	// After a click or tap, the new content grows in while the space of the old content collapses. The old content
+	// unmounts at once, so its payment handlers stop, and only an empty box takes its place: gateway scripts could
+	// find a copy of their fields. Key presses and changes in code apply immediately.
+	const rootRef = useRef< HTMLDivElement >( null );
+	const contentRef = useRef< HTMLDivElement >( null );
+	const animateRef = useRef( false );
+	useLayoutEffect( () => {
+		// Space that an earlier click still collapses, in any option, goes too.
+		if ( ! animateRef.current ) {
+			removeCollapseCopies( rootRef.current );
+		}
+		animateCollapse( contentRef.current, true, animateRef.current );
+		animateRef.current = false;
+	}, [ selected ] );
+
 	if ( ! options.length ) {
 		return null;
 	}
 	return (
 		<div
+			ref={ rootRef }
 			className={ clsx(
 				'wc-block-components-radio-control',
 				{
@@ -82,6 +103,15 @@ const RadioControlAccordion = ( {
 							checked={ checked }
 							option={ option }
 							onChange={ ( value ) => {
+								// Arrow keys leave focus visible on the radio. A click does not.
+								animateRef.current = ! document
+									.getElementById( `${ name }-${ value }` )
+									?.matches( ':focus-visible' );
+								if ( animateRef.current ) {
+									collapseCopy( contentRef.current, {
+										empty: true,
+									} );
+								}
 								onChange( value );
 								if ( typeof option.onChange === 'function' ) {
 									option.onChange( value );
@@ -90,6 +120,7 @@ const RadioControlAccordion = ( {
 						/>
 						{ hasOptionContent && checked && (
 							<div
+								ref={ contentRef }
 								id={ `${ name }-${ option.value }__content` }
 								className={ clsx(
 									'wc-block-components-radio-control-accordion-content',