Commit 67f915530b6 for woocommerce
commit 67f915530b61f0f31d61d67f9f894f233be5c425
Author: Mike Jolley <mike.jolley@me.com>
Date: Thu Nov 26 12:58:25 2026 +0000
Add motion to cart item removal (#70925)
* Add motion to cart item removal
A removed row fades in place, then the rows below slide up and the
table height closes in one movement. Keys apply at once.
* Leave no empty style attribute after a row removal
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.
* Keep the held margin when a second row removal takes over
A table with collapsed borders holds the space of a removal in its bottom margin, which the measured height left out. When a second removal took over before the first ended, the first space was dropped and the content below jumped up. Measure the bottom margin with the height.
* Recheck every element before whenAllAnimationsEnd calls back
Each element was counted once, so an element that ended and then started a new animation while another still ran did not hold back the callback. When the last element ends after a wait, check them all again.
* Remove the copies of a taken-over row removal at the safety timeout
The new removal's safety stop now removes every copy in the table, so a copy whose fade never ends can't outlive a takeover.
* Share the motion cleanup helpers in the row removal
The row removal uses `clearInlineStyle` and `MOTION_SAFETY_TIMEOUT`, and skips the layout reads when no row goes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Restore the table's own inline spacing after a row removal
The hold overwrote an inline bottom padding or margin on the table, then deleted it when the motion ended.
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-cart-removal b/plugins/woocommerce/changelog/add-cart-checkout-motion-cart-removal
new file mode 100644
index 00000000000..b2be0b6da8e
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-cart-checkout-motion-cart-removal
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Removing a product from the Cart block now fades it out, and the products below slide up into its place.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/index.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/index.tsx
index 2bb389e5795..83956bc0c0b 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/index.tsx
@@ -13,6 +13,7 @@ import { DelayedContentWithSkeleton } from '@woocommerce/base-components/delayed
* Internal dependencies
*/
import CartLineItemRow from './cart-line-item-row';
+import { useRowRemovalMotion } from './use-row-removal-motion';
import './style.scss';
interface CartLineItemsTableProps {
@@ -36,6 +37,10 @@ const CartLineItemsTable = ( {
}: CartLineItemsTableProps ): JSX.Element => {
const tableRef = useRef< HTMLTableElement | null >( null );
const rowRefs = useRef( setRefs( lineItems ) );
+ const onClickCapture = useRowRemovalMotion(
+ tableRef,
+ lineItems.map( ( { key } ) => key )
+ );
useEffect( () => {
rowRefs.current = setRefs( lineItems );
}, [ lineItems ] );
@@ -86,6 +91,7 @@ const CartLineItemsTable = ( {
className={ clsx( 'wc-block-cart-items', className ) }
ref={ tableRef }
tabIndex={ -1 }
+ onClickCapture={ onClickCapture }
>
<caption className="screen-reader-text">
<h2>{ __( 'Products in cart', 'woocommerce' ) }</h2>
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/style.scss b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/style.scss
index 6609e22f335..2bfc1b0d722 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/style.scss
@@ -135,6 +135,29 @@ table.wc-block-cart-items {
}
}
+// A removed row: a copy fades out in its place, then the rows below slide up and the space at the bottom of the table
+// closes. See `use-row-removal-motion.ts`.
+.wp-block-woocommerce-cart table.wc-block-cart-items {
+ > [data-wc-row-copy] {
+ @include motion-fade-out;
+
+ // The copy does not replay the entrance of the rows.
+ > tr {
+ animation: none;
+ }
+ }
+
+ &[data-wc-row-removal] {
+ @include motion-safe {
+ transition: motion-move((padding-bottom, margin-bottom), lg, balanced);
+ }
+
+ > tbody > tr {
+ @include motion-transition($state: opacity, $move: translate, $easing: balanced);
+ }
+ }
+}
+
@mixin cart-items-table-styles() {
table.wc-block-cart-items {
td {
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/test/use-row-removal-motion.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/test/use-row-removal-motion.tsx
new file mode 100644
index 00000000000..ab99a5ad6b3
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/test/use-row-removal-motion.tsx
@@ -0,0 +1,105 @@
+/**
+ * External dependencies
+ */
+import { act, render } from '@testing-library/react';
+import { useRef } from '@wordpress/element';
+
+/**
+ * Internal dependencies
+ */
+import { useRowRemovalMotion } from '../use-row-removal-motion';
+
+const Table = ( {
+ keys,
+ style,
+}: {
+ keys: string[];
+ style?: Record< string, string >;
+} ) => {
+ const tableRef = useRef< HTMLTableElement >( null );
+ useRowRemovalMotion( tableRef, keys );
+ return (
+ <div className="wp-block-woocommerce-cart">
+ <table ref={ tableRef } style={ style }>
+ <tbody>
+ { keys.map( ( key ) => (
+ <tr key={ key } data-cart-item-key={ key }>
+ <td>{ key }</td>
+ </tr>
+ ) ) }
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+// A fade that never reports its end.
+const stuckFade = {
+ playState: 'running',
+ effect: { getComputedTiming: () => ( { endTime: 200 } ) },
+ finished: new Promise( () => undefined ),
+};
+
+const copies = ( container: HTMLElement ) =>
+ container.querySelectorAll( '[data-wc-row-copy]' );
+
+describe( 'useRowRemovalMotion', () => {
+ beforeEach( () => {
+ jest.useFakeTimers();
+ Element.prototype.getAnimations = function ( this: Element ) {
+ return ( this.hasAttribute( 'data-wc-row-copy' )
+ ? [ stuckFade ]
+ : [] ) as unknown as Animation[];
+ };
+ } );
+
+ afterEach( () => {
+ jest.useRealTimers();
+ // @ts-expect-error Not in jsdom.
+ delete Element.prototype.getAnimations;
+ } );
+
+ it( 'removes the copies of a removal that a second removal took over when the fades never end', () => {
+ const { container, rerender } = render(
+ <Table keys={ [ 'a', 'b', 'c' ] } />
+ );
+ rerender( <Table keys={ [ 'b', 'c' ] } /> );
+ expect( copies( container ) ).toHaveLength( 1 );
+
+ act( () => {
+ jest.advanceTimersByTime( 500 );
+ } );
+ rerender( <Table keys={ [ 'c' ] } /> );
+ expect( copies( container ) ).toHaveLength( 2 );
+
+ act( () => {
+ jest.advanceTimersByTime( 1000 );
+ } );
+ expect( copies( container ) ).toHaveLength( 0 );
+ } );
+
+ it( 'puts back the inline spacing of the table after the hold', () => {
+ const rowHeight = 50;
+ const spy = jest
+ .spyOn( HTMLTableElement.prototype, 'getBoundingClientRect' )
+ .mockImplementation( function ( this: HTMLTableElement ) {
+ const height =
+ this.querySelectorAll( 'tr[data-cart-item-key]' ).length *
+ rowHeight;
+ return { top: 0, left: 0, width: 100, height } as DOMRect;
+ } );
+ const style = { paddingBottom: '24px' };
+ const { container, rerender } = render(
+ <Table keys={ [ 'a', 'b' ] } style={ style } />
+ );
+ const table = container.querySelector( 'table' ) as HTMLTableElement;
+ rerender( <Table keys={ [ 'b' ] } style={ style } /> );
+ expect( table.style.paddingBottom ).toBe( '74px' );
+
+ act( () => {
+ jest.advanceTimersByTime( 1000 );
+ } );
+ expect( table.style.paddingBottom ).toBe( '24px' );
+ spy.mockRestore();
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/use-row-removal-motion.ts b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/use-row-removal-motion.ts
new file mode 100644
index 00000000000..1582316efea
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/cart-line-items-table/use-row-removal-motion.ts
@@ -0,0 +1,258 @@
+/**
+ * External dependencies
+ */
+import { useEffect, useLayoutEffect, useRef } from '@wordpress/element';
+import {
+ MOTION_SAFETY_TIMEOUT,
+ clearInlineStyle,
+ inertCopy,
+ whenAnimationsEnd,
+ whenAllAnimationsEnd,
+} from '@woocommerce/base-utils';
+import type { MouseEvent, RefObject } from 'react';
+
+// The styles in `style.scss` use these attributes.
+const MOVING = 'data-wc-row-removal';
+const COPY = 'data-wc-row-copy';
+
+const ROW = 'tr[data-cart-item-key]';
+const ROWS = `:scope > tbody > ${ ROW }`;
+
+type RemovedRow = {
+ row: HTMLTableRowElement;
+ rect: DOMRect;
+ cellWidths: number[];
+};
+
+type Snapshot = {
+ removed: RemovedRow[];
+ // Where the rows that stay are on the screen, including a slide that still runs.
+ tops: Map< string, number >;
+ // The space the table takes, including a space that an earlier removal still holds.
+ height: number;
+};
+
+// Only the Cart block animates. The Mini Cart shares this table, and changes immediately.
+const canAnimate = (
+ table: HTMLTableElement | null
+): table is HTMLTableElement =>
+ typeof table?.getAnimations === 'function' &&
+ table.closest( '.wp-block-woocommerce-cart' ) !== null;
+
+const keyOf = ( row: HTMLTableRowElement ) => row.dataset.cartItemKey as string;
+
+// The bottom margin counts too: a table with collapsed borders holds the space of a removal in its margin.
+const heightOf = ( table: HTMLTableElement ) =>
+ table.getBoundingClientRect().height +
+ ( parseFloat( getComputedStyle( table ).marginBottom ) || 0 );
+
+const measure = (
+ table: HTMLTableElement,
+ keys: string[]
+): Snapshot | null => {
+ const rows = Array.from(
+ table.querySelectorAll< HTMLTableRowElement >( ROWS )
+ );
+ const kept = new Set( keys );
+ // Most changes add or reorder rows. Only read the layout when a row goes.
+ if ( rows.every( ( row ) => kept.has( keyOf( row ) ) ) ) {
+ return null;
+ }
+ const removed: RemovedRow[] = [];
+ const tops = new Map< string, number >();
+ rows.forEach( ( row ) => {
+ if ( kept.has( keyOf( row ) ) ) {
+ tops.set( keyOf( row ), row.getBoundingClientRect().top );
+ return;
+ }
+ removed.push( {
+ row,
+ rect: row.getBoundingClientRect(),
+ cellWidths: Array.from(
+ row.cells,
+ ( cell ) => cell.getBoundingClientRect().width
+ ),
+ } );
+ } );
+ return { removed, tops, height: heightOf( table ) };
+};
+
+// An inert copy of the row, in its own table box laid over the place where the row was. Table rows can't be
+// positioned, so the copy's body is the table, with the cell widths of the row.
+const placeCopy = (
+ table: HTMLTableElement,
+ { row, rect, cellWidths }: RemovedRow
+) => {
+ const copy = inertCopy( row ) as HTMLTableRowElement;
+ // Without its key, the copy is not a row of the cart.
+ copy.removeAttribute( 'data-cart-item-key' );
+ Array.from( copy.cells ).forEach( ( cell, index ) => {
+ cell.style.boxSizing = 'border-box';
+ cell.style.width = `${ cellWidths[ index ] ?? 0 }px`;
+ } );
+ const body = document.createElement( 'tbody' );
+ body.setAttribute( COPY, '' );
+ body.setAttribute( 'aria-hidden', 'true' );
+ Object.assign( body.style, {
+ position: 'absolute',
+ display: 'table',
+ tableLayout: 'fixed',
+ width: `${ rect.width }px`,
+ top: '0',
+ left: '0',
+ } );
+ body.append( copy );
+ table.append( body );
+ // At 0, the copy is at the corner of whichever element it is positioned against.
+ const origin = body.getBoundingClientRect();
+ body.style.top = `${ rect.top - origin.top }px`;
+ body.style.left = `${ rect.left - origin.left }px`;
+ return body;
+};
+
+/**
+ * Copies of the removed rows fade out where they were. The rows below and the space of the table hold their place
+ * until the copies have gone. Then the rows slide up, and the space at the bottom of the table closes in the real
+ * layout, so the content below moves one time. With reduced motion, the copies only fade.
+ *
+ * @return A function that ends the motion at once. Pass `true` to also remove the copies.
+ */
+const playRemoval = (
+ table: HTMLTableElement,
+ { removed, tops, height }: Snapshot
+) => {
+ let isStopped = false;
+ const cancels: Array< () => void > = [];
+ const copies = removed.map( ( item ) => placeCopy( table, item ) );
+ // Not cancelled when a new removal takes over, so each copy finishes its fade.
+ copies.forEach( ( copy ) =>
+ whenAnimationsEnd( copy, () => copy.remove() )
+ );
+
+ // Padding is the space at the bottom of the table, but a table with collapsed borders has none.
+ const space =
+ getComputedStyle( table ).borderCollapse === 'collapse'
+ ? 'margin-bottom'
+ : 'padding-bottom';
+ const lost = height - heightOf( table );
+ // A new row has no old place, so its offset is NaN, and it does not move.
+ const offsets = Array.from(
+ table.querySelectorAll< HTMLTableRowElement >( ROWS ),
+ ( row ) => ( {
+ row,
+ offset:
+ ( tops.get( keyOf( row ) ) ?? NaN ) -
+ row.getBoundingClientRect().top,
+ } )
+ ).filter( ( { offset } ) => Math.abs( offset ) >= 1 );
+ const moved = offsets.map( ( { row } ) => row );
+ offsets.forEach( ( { row, offset } ) => {
+ row.style.translate = `0 ${ offset }px`;
+ } );
+ // The table can have its own inline spacing, for example from an extension. Put it back after the hold.
+ const ownSpace = table.style.getPropertyValue( space );
+ const ownPriority = table.style.getPropertyPriority( space );
+ const releaseSpace = () =>
+ ownSpace
+ ? table.style.setProperty( space, ownSpace, ownPriority )
+ : clearInlineStyle( table, space );
+ if ( lost >= 1 ) {
+ const current = getComputedStyle( table ).getPropertyValue( space );
+ table.style.setProperty( space, `${ parseFloat( current ) + lost }px` );
+ }
+
+ const stop = ( removeCopies: boolean ) => {
+ if ( isStopped ) {
+ return;
+ }
+ isStopped = true;
+ cancels.forEach( ( cancel ) => cancel() );
+ table.removeAttribute( MOVING );
+ releaseSpace();
+ moved.forEach( ( row ) => clearInlineStyle( row, 'translate' ) );
+ if ( removeCopies ) {
+ // Includes the copies of a removal that this one took over, which still fade out.
+ table
+ .querySelectorAll( `:scope > [${ COPY }]` )
+ .forEach( ( copy ) => copy.remove() );
+ }
+ };
+
+ const release = () => {
+ table.setAttribute( MOVING, '' );
+ releaseSpace();
+ moved.forEach( ( row ) => clearInlineStyle( row, 'translate' ) );
+ cancels.push(
+ whenAllAnimationsEnd( [ table, ...moved ], () => stop( false ) )
+ );
+ };
+
+ cancels.push( whenAllAnimationsEnd( copies, release ) );
+ const safety = window.setTimeout(
+ () => stop( true ),
+ MOTION_SAFETY_TIMEOUT
+ );
+ cancels.push( () => window.clearTimeout( safety ) );
+ return stop;
+};
+
+/**
+ * Animates the rows that leave the cart table. The real rows unmount as before, and only inert copies animate. A row
+ * that the shopper removed with the keyboard goes immediately.
+ *
+ * @param tableRef The cart table.
+ * @param keys The keys of the rows to render.
+ * @return A click handler for the table, which notes how each row was last clicked.
+ */
+export const useRowRemovalMotion = (
+ tableRef: RefObject< HTMLTableElement >,
+ keys: string[]
+) => {
+ const keyList = keys.join();
+ const lastKeyList = useRef( keyList );
+ const snapshot = useRef< Snapshot | null >( null );
+ const stop = useRef< ( ( removeCopies: boolean ) => void ) | null >( null );
+ const keyboardKeys = useRef( new Set< string >() );
+
+ // Measure while the removed rows are still in the page: React removes them before the layout effect runs.
+ if ( lastKeyList.current !== keyList ) {
+ lastKeyList.current = keyList;
+ snapshot.current = canAnimate( tableRef.current )
+ ? measure( tableRef.current, keys )
+ : null;
+ }
+
+ useLayoutEffect( () => {
+ const table = tableRef.current;
+ const removal = snapshot.current;
+ snapshot.current = null;
+ if ( ! removal || ! table ) {
+ return;
+ }
+ const removedKeys = removal.removed.map( ( { row } ) => keyOf( row ) );
+ const isKeyboard = removedKeys.some( ( key ) =>
+ keyboardKeys.current.has( key )
+ );
+ removedKeys.forEach( ( key ) => keyboardKeys.current.delete( key ) );
+ stop.current?.( isKeyboard );
+ stop.current = isKeyboard ? null : playRemoval( table, removal );
+ } );
+
+ useEffect( () => () => stop.current?.( true ), [] );
+
+ // A keyboard click has no click count.
+ return ( event: MouseEvent ) => {
+ const row =
+ event.target instanceof Element
+ ? event.target.closest< HTMLTableRowElement >( ROW )
+ : null;
+ if ( ! row ) {
+ return;
+ }
+ if ( event.detail === 0 ) {
+ keyboardKeys.current.add( keyOf( row ) );
+ } else {
+ keyboardKeys.current.delete( keyOf( row ) );
+ }
+ };
+};
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/swap-sections.ts b/plugins/woocommerce/client/blocks/assets/js/base/utils/swap-sections.ts
index 679e2651e7b..e6275d074bd 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/utils/swap-sections.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/swap-sections.ts
@@ -6,7 +6,7 @@ import {
clearInlineStyle,
inertCopy,
} from './animate-collapse';
-import { whenAnimationsEnd } from './when-animations-end';
+import { whenAnimationsEnd, whenAllAnimationsEnd } from './when-animations-end';
// The `motion-swap` mixin styles the container, the copies, and the sections by these attributes.
const SWAPPING = 'data-wc-swapping';
@@ -39,27 +39,6 @@ const sectionsOf = ( container: HTMLElement ) =>
child instanceof HTMLElement && ! child.hasAttribute( COPY )
);
-// Runs `callback` when the animations of all `elements` end. Returns a function that cancels it.
-const whenAllAnimationsEnd = (
- elements: Element[],
- callback: () => void
-): ( () => void ) => {
- let pending = elements.length;
- if ( pending === 0 ) {
- callback();
- return () => undefined;
- }
- const cancels = elements.map( ( element ) =>
- whenAnimationsEnd( element, () => {
- pending--;
- if ( pending === 0 ) {
- callback();
- }
- } )
- );
- return () => cancels.forEach( ( cancel ) => cancel() );
-};
-
/**
* Splits the sections of a swap. The group runs from the first section that changes to the last, in the old order and
* in the new one, and includes the sections between them that stay. The sections after the group stay where they are
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/test/when-animations-end.ts b/plugins/woocommerce/client/blocks/assets/js/base/utils/test/when-animations-end.ts
index c99a4fd1707..b9c317abc38 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/utils/test/when-animations-end.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/test/when-animations-end.ts
@@ -1,7 +1,10 @@
/**
* Internal dependencies
*/
-import { whenAnimationsEnd } from '../when-animations-end';
+import {
+ whenAnimationsEnd,
+ whenAllAnimationsEnd,
+} from '../when-animations-end';
// Jest has no Web Animations API. Like a browser animation, this fake reports `finished` or `idle` when it ends.
const createAnimation = (
@@ -125,3 +128,72 @@ describe( 'whenAnimationsEnd', () => {
expect( callback ).not.toHaveBeenCalled();
} );
} );
+
+describe( 'whenAllAnimationsEnd', () => {
+ it( 'calls back immediately when there are no elements', () => {
+ const callback = jest.fn();
+ whenAllAnimationsEnd( [], callback );
+ expect( callback ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'waits for the animations of every element to end', async () => {
+ const callback = jest.fn();
+ const first = createAnimation();
+ const second = createAnimation();
+ whenAllAnimationsEnd(
+ [
+ createElement( [ first.animation ] ),
+ createElement( [ second.animation ] ),
+ ],
+ callback
+ );
+
+ first.finish();
+ await flushPromises();
+ expect( callback ).not.toHaveBeenCalled();
+
+ second.finish();
+ await flushPromises();
+ expect( callback ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'waits again for an element that starts a new animation while another still runs', async () => {
+ const callback = jest.fn();
+ const first = createAnimation();
+ const second = createAnimation();
+ const restarted = createAnimation();
+ const firstAnimations = [ first.animation ];
+ whenAllAnimationsEnd(
+ [
+ createElement( firstAnimations ),
+ createElement( [ second.animation ] ),
+ ],
+ callback
+ );
+
+ first.finish();
+ await flushPromises();
+ firstAnimations.push( restarted.animation );
+ second.finish();
+ await flushPromises();
+ expect( callback ).not.toHaveBeenCalled();
+
+ restarted.finish();
+ await flushPromises();
+ expect( callback ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'does not call back after it is cancelled', async () => {
+ const callback = jest.fn();
+ const animation = createAnimation();
+ const cancel = whenAllAnimationsEnd(
+ [ createElement( [ animation.animation ] ) ],
+ callback
+ );
+
+ cancel();
+ animation.finish();
+ await flushPromises();
+ expect( callback ).not.toHaveBeenCalled();
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/utils/when-animations-end.ts b/plugins/woocommerce/client/blocks/assets/js/base/utils/when-animations-end.ts
index a60c4857ffb..06ff621e55b 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/utils/when-animations-end.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/utils/when-animations-end.ts
@@ -52,3 +52,42 @@ export const whenAnimationsEnd = (
isCancelled = true;
};
};
+
+/**
+ * Calls `callback` when the animations of all `elements` end. See `whenAnimationsEnd`.
+ *
+ * @param elements The elements that animate.
+ * @param callback Runs one time, when no animation of any element is in progress.
+ * @return A function that cancels the callback.
+ */
+export const whenAllAnimationsEnd = (
+ elements: Element[],
+ callback: () => void
+): ( () => void ) => {
+ if ( elements.length === 0 ) {
+ callback();
+ return () => undefined;
+ }
+ let cancels: Array< () => void > = [];
+ const waitForAll = () => {
+ let pending = elements.length;
+ let hasWaited = false;
+ cancels = elements.map( ( element ) =>
+ whenAnimationsEnd( element, () => {
+ pending--;
+ if ( pending > 0 ) {
+ return;
+ }
+ // An element that ended can start a new animation while another still runs, so check them all again.
+ if ( hasWaited ) {
+ waitForAll();
+ } else {
+ callback();
+ }
+ } )
+ );
+ hasWaited = true;
+ };
+ waitForAll();
+ return () => cancels.forEach( ( cancel ) => cancel() );
+};
diff --git a/plugins/woocommerce/client/blocks/docs/contributors/motion.md b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
index 243a3cc7765..c76ac2b3410 100644
--- a/plugins/woocommerce/client/blocks/docs/contributors/motion.md
+++ b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
@@ -92,7 +92,7 @@ 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. |
+| `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. `whenAllAnimationsEnd( elements, callback )` waits for all of `elements`. |
| `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. |
@@ -121,7 +121,7 @@ Find the change in this table, and use the helpers above.
| The selection moves to another option, such as Ship or Pickup | A copy of the selected style slides to the new option, and stretches a little on the way. |
| A choice swaps a group of sections, such as Ship or Pickup | The old sections fade out and move 24px the way that the selection moved. Then the new sections fade in and slide in from the other side. The sections after them hold their place until the old sections have gone, then move one time. With reduced motion, the layout changes at once, and the new sections fade in. |
| An element becomes a different view of itself, such as an address card that becomes its form | The two views crossfade while the height changes. |
-| A table row goes | It fades in place, and the rows below slide up. |
+| A table row goes | An inert copy fades in place. Then the rows below slide up, and the space at the bottom of the table closes. |
Real layout means the element's height, padding, borders, and margins change, so theme spacing and extension markup move with it. Use `transform` for everything else.