Commit 3e7707918f2 for woocommerce
commit 3e7707918f2fb102017519177feb43f5aba0f3f1
Author: Mike Jolley <mike.jolley@me.com>
Date: Thu Nov 26 12:58:24 2026 +0000
Add motion to Checkout address forms (#70889)
* Add motion to the Checkout address forms
The billing section grows and collapses with the shipping-as-billing
checkbox, the address card eases its height into the form, and the
address line 2 field grows in. Only on click; keys apply at once. A
hidden billing form unmounts at once and an inert copy collapses.
* Share the toggle collapse between billing and address line 2
useToggleCollapse grows content that a control shows after a click,
collapses an inert copy when it hides, and applies key presses at once.
Later sections reuse it.
* Keep collapse copy fields out of form validation
The copy of a collapsing form kept required fields, so an empty one made form.checkValidity() fail and matched input:invalid until the collapse ended. Make the copied fields read-only and drop required, rather than disabling them, which browsers grey out.
diff --git a/plugins/woocommerce/changelog/add-cart-checkout-motion-address-forms b/plugins/woocommerce/changelog/add-cart-checkout-motion-address-forms
new file mode 100644
index 00000000000..3a507142834
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-cart-checkout-motion-address-forms
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Checkout address forms now grow and collapse smoothly when the billing address, an address form, or the apartment field is shown.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/address-line-2-field.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/address-line-2-field.tsx
index 75ce9ab5732..1fefb9db6e8 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/address-line-2-field.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/address-line-2-field.tsx
@@ -3,7 +3,7 @@
*/
import { ValidatedTextInput } from '@woocommerce/blocks-components';
import { useState, Fragment, useCallback, useEffect } from '@wordpress/element';
-import { usePrevious } from '@woocommerce/base-hooks';
+import { usePrevious, useToggleCollapse } from '@woocommerce/base-hooks';
import { __, sprintf } from '@wordpress/i18n';
import { Button } from '@ariakit/react';
import { getFieldLabel } from '@woocommerce/blocks-checkout';
@@ -50,6 +50,21 @@ const AddressLine2Field = ( {
}
}, [ value ] );
+ // The field grows from the height of the "+ Add" link that a click replaced, so that the content below moves in one
+ // direction.
+ const fieldCollapse = useToggleCollapse(
+ Boolean( isFieldVisible ),
+ () =>
+ ( props?.id &&
+ document
+ .getElementById( props.id )
+ ?.closest< HTMLElement >(
+ '.wc-block-components-address-form__address_2'
+ ) ) ||
+ null,
+ { growFromTrigger: true }
+ );
+
return (
<Fragment>
{ isFieldVisible ? (
@@ -70,7 +85,10 @@ const AddressLine2Field = ( {
className={
'wc-block-components-address-form__address_2-toggle'
}
- onClick={ () => setIsFieldVisible( true ) }
+ onClick={ ( event ) => {
+ fieldCollapse.onToggle( event );
+ setIsFieldVisible( true );
+ } }
>
{ sprintf(
// translators: %s: address 2 field label.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/hooks/index.js b/plugins/woocommerce/client/blocks/assets/js/base/hooks/index.js
index ceaf1ec9a8a..c0310e70907 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/hooks/index.js
+++ b/plugins/woocommerce/client/blocks/assets/js/base/hooks/index.js
@@ -13,3 +13,4 @@ export * from './use-schema-parser';
export * from './use-query-loop-product-context-validation';
export * from './use-preview-mode';
export * from './use-presence';
+export * from './use-toggle-collapse';
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-toggle-collapse.tsx b/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-toggle-collapse.tsx
new file mode 100644
index 00000000000..47ab2024a7f
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/hooks/test/use-toggle-collapse.tsx
@@ -0,0 +1,105 @@
+/**
+ * External dependencies
+ */
+import { act, render, screen } from '@testing-library/react';
+import { animateCollapse, collapseCopy } from '@woocommerce/base-utils';
+import { useState } from '@wordpress/element';
+
+/**
+ * Internal dependencies
+ */
+import { useToggleCollapse } from '../use-toggle-collapse';
+
+jest.mock( '@woocommerce/base-utils', () => ( {
+ animateCollapse: jest.fn(),
+ collapseCopy: jest.fn(),
+} ) );
+
+let toggle: ( event?: { detail: number } ) => void;
+
+const Section = ( {
+ initialShown = false,
+ growFromTrigger = false,
+}: {
+ initialShown?: boolean;
+ growFromTrigger?: boolean;
+} ) => {
+ const [ isShown, setIsShown ] = useState( initialShown );
+ const { triggerRef, onToggle } = useToggleCollapse< HTMLButtonElement >(
+ isShown,
+ () => document.getElementById( 'content' ),
+ { growFromTrigger }
+ );
+ toggle = ( event ) => {
+ onToggle( event && { ...event, currentTarget: triggerRef.current } );
+ setIsShown( ! isShown );
+ };
+ return (
+ <>
+ <button ref={ triggerRef }>Toggle</button>
+ { isShown && <div id="content" /> }
+ </>
+ );
+};
+
+describe( 'useToggleCollapse', () => {
+ beforeEach( () => {
+ jest.clearAllMocks();
+ } );
+
+ it( 'grows the content after a click', () => {
+ render( <Section /> );
+ act( () => toggle( { detail: 1 } ) );
+ expect( animateCollapse ).toHaveBeenLastCalledWith(
+ screen.getByRole( 'button' ).nextElementSibling,
+ true,
+ true,
+ undefined
+ );
+ } );
+
+ it( 'grows the content from the height of the control', () => {
+ render( <Section growFromTrigger /> );
+ jest.spyOn(
+ screen.getByRole( 'button' ),
+ 'offsetHeight',
+ 'get'
+ ).mockReturnValue( 24 );
+ act( () => toggle( { detail: 1 } ) );
+ expect( animateCollapse ).toHaveBeenLastCalledWith(
+ expect.any( HTMLElement ),
+ true,
+ true,
+ { height: '24px', opacity: '0' }
+ );
+ } );
+
+ it( 'collapses a copy of the content after a click', () => {
+ render( <Section initialShown /> );
+ const content = document.getElementById( 'content' );
+ act( () => toggle( { detail: 1 } ) );
+ expect( collapseCopy ).toHaveBeenCalledWith( content );
+ } );
+
+ it( 'applies a key press immediately', () => {
+ render( <Section initialShown /> );
+ act( () => toggle( { detail: 0 } ) );
+ expect( collapseCopy ).not.toHaveBeenCalled();
+ act( () => toggle( { detail: 0 } ) );
+ expect( animateCollapse ).toHaveBeenLastCalledWith(
+ expect.any( HTMLElement ),
+ true,
+ false,
+ undefined
+ );
+ } );
+
+ it( 'applies a key press immediately when focus is visible on the control', () => {
+ render( <Section initialShown /> );
+ jest.spyOn( screen.getByRole( 'button' ), 'matches' ).mockReturnValue(
+ true
+ );
+ act( () => toggle() );
+ expect( collapseCopy ).not.toHaveBeenCalled();
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-toggle-collapse.ts b/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-toggle-collapse.ts
new file mode 100644
index 00000000000..e97741ed549
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/hooks/use-toggle-collapse.ts
@@ -0,0 +1,74 @@
+/**
+ * External dependencies
+ */
+import { useLayoutEffect, useRef } from '@wordpress/element';
+import { animateCollapse, collapseCopy } from '@woocommerce/base-utils';
+
+/**
+ * For content that a control shows and hides, such as a checkbox that reveals a field. After a click or tap, the
+ * content grows in the real layout when it shows. When it goes, it unmounts at once, so that its fields stop counting,
+ * and an inert copy collapses in its place. A key press, page load, and changes in code apply immediately.
+ *
+ * Call `onToggle` in the handler of the control, before the state changes. Pass the click event when there is one: a
+ * click that a key press starts has no click count. Otherwise, put `triggerRef` on the control: a key press leaves
+ * focus visible on it, and a click does not.
+ *
+ * @param isShown Whether the content shows.
+ * @param getElement Returns the element that grows and collapses. Give it the `motion-collapse` mixin.
+ * Find it by id, or skip `[data-wc-collapse-copy]`: the copy keeps the element's classes
+ * and comes first, so a class selector alone finds the copy while it collapses.
+ * @param options
+ * @param options.growFromTrigger Set to `true` when the content replaces the control, so that it grows from the height
+ * of the control, and the content below moves in one direction.
+ * @return The ref for the control, and the function to call when the shopper uses it.
+ */
+export const useToggleCollapse = < E extends HTMLElement = HTMLInputElement >(
+ isShown: boolean,
+ getElement: () => HTMLElement | null,
+ { growFromTrigger = false }: { growFromTrigger?: boolean } = {}
+) => {
+ const triggerRef = useRef< E >( null );
+ const animateRef = useRef( false );
+ const fromHeightRef = useRef< number | null >( null );
+ // The element is read when the motion starts, not when the component renders.
+ const getElementRef = useRef( getElement );
+ getElementRef.current = getElement;
+
+ useLayoutEffect( () => {
+ if ( isShown ) {
+ animateCollapse(
+ getElementRef.current(),
+ true,
+ animateRef.current,
+ fromHeightRef.current === null
+ ? undefined
+ : { height: `${ fromHeightRef.current }px`, opacity: '0' }
+ );
+ }
+ animateRef.current = false;
+ fromHeightRef.current = null;
+ }, [ isShown ] );
+
+ const onToggle = ( event?: {
+ detail: number;
+ currentTarget: EventTarget | null;
+ } ) => {
+ const trigger = event ? event.currentTarget : triggerRef.current;
+ animateRef.current =
+ trigger instanceof HTMLElement &&
+ ( event
+ ? event.detail !== 0
+ : ! trigger.matches( ':focus-visible' ) );
+ fromHeightRef.current =
+ animateRef.current &&
+ growFromTrigger &&
+ trigger instanceof HTMLElement
+ ? trigger.offsetHeight
+ : null;
+ if ( isShown && animateRef.current ) {
+ collapseCopy( getElementRef.current() );
+ }
+ };
+
+ return { triggerRef, onToggle };
+};
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 3f045bde883..aa0aa9ac40e 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
@@ -7,6 +7,9 @@ import { whenAnimationsEnd } from './when-animations-end';
// in the module, because each script bundle has its own copy of this module.
const ATTRIBUTE = 'data-wc-collapse';
+// Marks the copy that `collapseCopy` puts in the place of an element, with the class name of the element.
+const COPY = 'data-wc-collapse-copy';
+
// The properties that make the space, and the fade.
const PROPERTIES = [
'height',
@@ -64,11 +67,17 @@ const reset = ( element: HTMLElement ) => {
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 ) => {
+// Moves the element from `current`, or from its rest position, to open or closed. A grow from rest starts from `from`.
+const move = (
+ element: HTMLElement,
+ isOpen: boolean,
+ current: Values | null,
+ from?: Partial< Values >
+) => {
reset( element );
const open = readValues( element );
- const start = from ?? ( isOpen ? CLOSED : open );
+ const closed = from ? { ...open, ...from } : CLOSED;
+ const start = current ?? ( isOpen ? closed : open );
// Nothing to grow, such as when the content kept its size during the grow.
if (
isOpen &&
@@ -102,30 +111,86 @@ const move = ( element: HTMLElement, isOpen: boolean, from: Values | null ) => {
* 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
+ * still moves, the motion turns around from its current position. This includes a copy of the element that
+ * `collapseCopy` still collapses in its place. 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.
+ * @param from Grows from these values instead of from nothing, such as the height of the content that the element
+ * replaces. The values that it does not set start open.
*/
export const animateCollapse = (
element: HTMLElement | null,
isOpen: boolean,
- animate = true
+ animate = true,
+ from?: Partial< Values >
): void => {
if ( typeof element?.getAnimations !== 'function' ) {
return;
}
+ const copy = isOpen ? element.previousElementSibling : null;
+ const hasCopy =
+ copy instanceof HTMLElement &&
+ copy.getAttribute( COPY ) === element.className;
// While the motion runs, the computed style is its current position.
- const current = element.hasAttribute( ATTRIBUTE )
- ? readValues( element )
- : null;
+ let current: Values | null = null;
+ if ( hasCopy ) {
+ current = readValues( copy );
+ copy.remove();
+ } else if ( element.hasAttribute( ATTRIBUTE ) ) {
+ current = readValues( element );
+ }
if ( ! animate ) {
reset( element );
return;
}
- move( element, isOpen, current );
+ move( element, isOpen, current, from );
+};
+
+/**
+ * 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, its
+ * fields are not validated, 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.
+ */
+export const collapseCopy = ( element: HTMLElement | null ): void => {
+ if ( typeof element?.getAnimations !== 'function' ) {
+ return;
+ }
+ const copy = element.cloneNode( true ) as HTMLElement;
+ [
+ copy,
+ ...Array.from( copy.querySelectorAll( '[id], [name], [for]' ) ),
+ ].forEach( ( node ) => {
+ node.removeAttribute( 'id' );
+ node.removeAttribute( 'name' );
+ node.removeAttribute( 'for' );
+ } );
+ // A clone shows the first option of a select, not the selected one.
+ const selects = element.querySelectorAll( 'select' );
+ copy.querySelectorAll( 'select' ).forEach( ( select, index ) => {
+ select.selectedIndex = selects[ index ].selectedIndex;
+ } );
+ // Keeps the fields out of form validation and `:invalid`. Disabled would do it too, but browsers grey it out.
+ // Read-only fields are not validated, and checkboxes, radios, and selects only check `required`.
+ copy.querySelectorAll( 'input, select, textarea' ).forEach( ( control ) => {
+ control.setAttribute( 'readonly', '' );
+ control.removeAttribute( 'required' );
+ } );
+ copy.setAttribute( 'inert', '' );
+ copy.setAttribute( 'aria-hidden', 'true' );
+ copy.setAttribute( COPY, element.className );
+ // A motion that runs continues from its current position.
+ if ( element.hasAttribute( ATTRIBUTE ) ) {
+ Object.assign( copy.style, readValues( element ) );
+ }
+ element.after( copy );
+ animateCollapse( copy, false );
+ whenAnimationsEnd( 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 49f52209976..f1481e9a726 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,7 @@
/**
* Internal dependencies
*/
-import { animateCollapse } from '../animate-collapse';
+import { animateCollapse, collapseCopy } from '../animate-collapse';
const NATURAL: Record< string, string > = {
height: '40px',
@@ -12,78 +12,107 @@ const NATURAL: Record< string, string > = {
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;
+// Jest has no layout, transitions, or Web Animations API. In the fake, the computed style of an element is the inline
+// style, or its `natural` value when there is none. While the `inProgress` values of an element are set and it has the
+// attribute of the helper, a transition is at those values. Each time the helper sets its attribute on an element, a
+// new transition starts and replaces the running one of that element, as in a browser. `finish` ends the running
+// transitions of all elements, including copies.
+type FakeTransition = {
+ playState: string;
+ finished: Promise< void >;
+ effect: { getComputedTiming: () => { endTime: number } };
+ end: () => void;
+ cancel: () => void;
+};
+const inProgress = new WeakMap< Element, Record< string, string > >();
+const naturals = new WeakMap< Element, Record< string, string > >();
+const transitions = new Map< Element, FakeTransition >();
+const setAttribute = Element.prototype.setAttribute;
+
+const startTransition = ( element: Element ) => {
+ transitions.get( element )?.cancel();
+ let end = () => undefined as void;
+ let cancel = () => undefined as void;
+ const finished = new Promise< void >( ( resolve, reject ) => {
+ end = resolve;
+ cancel = reject;
+ } );
+ finished.catch( () => undefined );
+ const transition: FakeTransition = {
+ playState: 'running',
+ finished,
+ effect: { getComputedTiming: () => ( { endTime: 300 } ) },
+ end: () => {
+ transition.playState = 'finished';
+ end();
+ },
+ cancel: () => {
+ transition.playState = 'idle';
+ cancel();
+ },
};
- const setAttribute = element.setAttribute.bind( element );
- element.setAttribute = ( name: string, value: string ) => {
- setAttribute( name, value );
- if ( name === 'data-wc-collapse' ) {
- startTransition();
+ transitions.set( element, transition );
+};
+
+const setUp = () => {
+ jest.spyOn( Element.prototype, 'setAttribute' ).mockImplementation(
+ function ( this: Element, name: string, value: string ) {
+ setAttribute.call( this, name, value );
+ if ( name === 'data-wc-collapse' ) {
+ startTransition( this );
+ }
}
- };
- element.getAnimations = () =>
- element.hasAttribute( 'data-wc-collapse' ) &&
- transition?.playState === 'running'
+ );
+ HTMLElement.prototype.getAnimations = function ( this: HTMLElement ) {
+ const transition = transitions.get( this );
+ return this.hasAttribute( 'data-wc-collapse' ) &&
+ transition?.playState === 'running'
? [ transition as unknown as Animation ]
: [];
+ };
jest.spyOn( window, 'getComputedStyle' ).mockImplementation(
- () =>
+ ( element ) =>
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 ],
+ inProgress.get( element )?.[ property ] ) ||
+ (
+ ( element as HTMLElement ).style as unknown as Record<
+ string,
+ string
+ >
+ )[ property ] ||
+ ( naturals.get( element ) ?? NATURAL )[ property ],
} )
);
+};
+
+const createElement = () => {
+ setUp();
+ const element = document.createElement( 'div' );
+ const values: Record< string, string > = {};
+ inProgress.set( element, values );
+ const natural = { ...NATURAL };
+ naturals.set( element, natural );
const finish = async () => {
- transition?.end();
+ transitions.forEach( ( transition ) => {
+ if ( transition.playState === 'running' ) {
+ transition.end();
+ }
+ } );
await new Promise( ( resolve ) => setTimeout( resolve ) );
};
- return { element, inProgress, natural, finish };
+ return { element, inProgress: values, natural, finish };
};
+afterEach( () => transitions.clear() );
+
describe( 'animateCollapse', () => {
- afterEach( () => jest.restoreAllMocks() );
+ afterEach( () => {
+ jest.restoreAllMocks();
+ // @ts-expect-error The fake is not part of jsdom.
+ delete HTMLElement.prototype.getAnimations;
+ } );
it( 'does nothing when the browser has no Web Animations API', () => {
const element = document.createElement( 'div' );
@@ -107,6 +136,24 @@ describe( 'animateCollapse', () => {
expect( element.getAttribute( 'data-wc-collapse' ) ).toBe( 'in' );
} );
+ it( 'grows from the values in `from`, and the other values start open', () => {
+ const { element } = createElement();
+ const setHeight = jest.spyOn( element.style, 'height', 'set' );
+ const setMarginTop = jest.spyOn( element.style, 'marginTop', 'set' );
+ animateCollapse( element, true, true, { height: '20px' } );
+
+ expect( setHeight.mock.calls ).toEqual( [
+ [ '' ],
+ [ '20px' ],
+ [ '40px' ],
+ ] );
+ expect( setMarginTop.mock.calls ).toEqual( [
+ [ '' ],
+ [ '16px' ],
+ [ '16px' ],
+ ] );
+ } );
+
it( 'leaves nothing behind when the grow ends', async () => {
const { element, finish } = createElement();
animateCollapse( element, true );
@@ -147,10 +194,10 @@ describe( 'animateCollapse', () => {
} );
it( 'turns around from the current position', async () => {
- const { element, inProgress, finish } = createElement();
+ const { element, inProgress: values, finish } = createElement();
const setHeight = jest.spyOn( element.style, 'height', 'set' );
animateCollapse( element, true );
- Object.assign( inProgress, { height: '10px', marginTop: '4px' } );
+ Object.assign( values, { height: '10px', marginTop: '4px' } );
setHeight.mockClear();
animateCollapse( element, false );
@@ -174,3 +221,124 @@ describe( 'animateCollapse', () => {
expect( element.getAttributeNames() ).toEqual( [] );
} );
} );
+
+describe( 'collapseCopy', () => {
+ afterEach( () => {
+ jest.restoreAllMocks();
+ document.body.innerHTML = '';
+ // @ts-expect-error The fake is not part of jsdom.
+ delete HTMLElement.prototype.getAnimations;
+ } );
+
+ const createForm = () => {
+ const { element, inProgress: values, finish } = createElement();
+ element.id = 'billing-fields';
+ element.className = 'billing';
+ element.innerHTML = `
+ <label for="city">City</label>
+ <input id="city" name="city" value="Berlin">
+ <select name="country"><option>Austria</option><option>Germany</option></select>
+ `;
+ // React sets the selected option as a property, which a clone does not keep.
+ (
+ element.querySelector( 'select' ) as HTMLSelectElement
+ ).selectedIndex = 1;
+ const parent = document.createElement( 'div' );
+ parent.append( element, document.createElement( 'p' ) );
+ document.body.append( parent );
+ return { element, parent, inProgress: values, finish };
+ };
+
+ it( 'does nothing when the browser has no Web Animations API', () => {
+ const parent = document.createElement( 'div' );
+ const element = document.createElement( 'div' );
+ parent.append( element );
+ collapseCopy( element );
+ collapseCopy( null );
+ expect( parent.children ).toHaveLength( 1 );
+ } );
+
+ it( 'collapses an inert copy that is not part of the form, and removes it when the collapse ends', async () => {
+ const { element, parent, finish } = createForm();
+ collapseCopy( element );
+
+ const copy = element.nextElementSibling as HTMLElement;
+ expect( copy.getAttribute( 'data-wc-collapse' ) ).toBe( 'out' );
+ expect( copy.hasAttribute( 'inert' ) ).toBe( true );
+ expect( copy.getAttribute( 'aria-hidden' ) ).toBe( 'true' );
+ expect( copy.querySelectorAll( '[id], [name], [for]' ) ).toHaveLength(
+ 0
+ );
+ expect( copy.hasAttribute( 'id' ) ).toBe( false );
+ expect( copy.querySelector( 'select' )?.selectedIndex ).toBe( 1 );
+ expect( element.getAttributeNames() ).toEqual( [ 'id', 'class' ] );
+
+ await finish();
+ expect( parent.children ).toHaveLength( 2 );
+ expect( parent.querySelector( '[data-wc-collapse-copy]' ) ).toBeNull();
+ } );
+
+ it( 'continues the motion of an element that still grows', () => {
+ const { element, inProgress: values } = createForm();
+ animateCollapse( element, true );
+ Object.assign( values, { height: '10px' } );
+
+ // The helper reads the layout once the start values are set.
+ const startHeights: string[] = [];
+ jest.spyOn(
+ HTMLElement.prototype,
+ 'getBoundingClientRect'
+ ).mockImplementation( function ( this: HTMLElement ) {
+ startHeights.push( this.style.height );
+ return {} as DOMRect;
+ } );
+ collapseCopy( element );
+ const copy = element.nextElementSibling as HTMLElement;
+ expect( startHeights ).toEqual( [ '10px' ] );
+ expect( copy.style.height ).toBe( '0px' );
+ } );
+
+ it( 'keeps the fields of the copy out of form validation', () => {
+ const { element } = createForm();
+ element.innerHTML = `
+ <input required>
+ <input type="email" value="not-an-email">
+ <input type="checkbox" required>
+ <select required><option value="">Select</option></select>
+ <textarea required></textarea>
+ `;
+ const form = document.createElement( 'form' );
+ element.before( form );
+ form.append( element );
+ collapseCopy( element );
+ element.remove();
+
+ expect(
+ form.querySelector( '[data-wc-collapse-copy]' )
+ ).not.toBeNull();
+ expect( form.checkValidity() ).toBe( true );
+ } );
+
+ it( 'turns around when the element grows again before the copy has collapsed', () => {
+ const { element } = createForm();
+ collapseCopy( element );
+ const copy = element.nextElementSibling as HTMLElement;
+ inProgress.set( copy, { height: '25px' } );
+
+ // React mounts a new element after the copy.
+ const next = document.createElement( 'div' );
+ next.className = 'billing';
+ inProgress.set( next, {} );
+ element.remove();
+ copy.after( next );
+ const setHeight = jest.spyOn( next.style, 'height', 'set' );
+ animateCollapse( next, true );
+
+ expect( copy.isConnected ).toBe( false );
+ expect( setHeight.mock.calls ).toEqual( [
+ [ '' ],
+ [ '25px' ],
+ [ '40px' ],
+ ] );
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-card/index.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-card/index.tsx
index 60880963b10..4568cf8379e 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-card/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-card/index.tsx
@@ -15,6 +15,7 @@ import { Button } from '@ariakit/react';
import { decodeEntities } from '@wordpress/html-entities';
import clsx from 'clsx';
import { useMemo } from '@wordpress/element';
+import type { MouseEvent } from 'react';
/**
* Internal dependencies
@@ -23,7 +24,7 @@ import './style.scss';
type Props = {
address: CartShippingAddress | CartBillingAddress;
- onEdit: () => void;
+ onEdit: ( event: MouseEvent ) => void;
target: string;
isExpanded: boolean;
};
@@ -96,7 +97,7 @@ const AddressCard = ( { address, onEdit, target, isExpanded }: Props ) => {
aria-label={ label }
onClick={ ( e ) => {
e.preventDefault();
- onEdit();
+ onEdit( e );
} }
type="button"
>
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/index.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/index.tsx
index 8a263d00378..2b1c1846d5d 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/index.tsx
@@ -2,6 +2,8 @@
* External dependencies
*/
import clsx from 'clsx';
+import { useLayoutEffect, useRef } from '@wordpress/element';
+import { animateCollapse } from '@woocommerce/base-utils';
/**
* Internal dependencies
@@ -10,7 +12,7 @@ import './style.scss';
/**
* Wrapper for address fields which handles the edit/preview transition. Form fields are always rendered so that
- * validation can occur.
+ * validation can occur. With `shouldAnimate`, the card and the form crossfade while the height changes.
*/
export const AddressWrapper = ( {
isEditing = false,
@@ -23,6 +25,19 @@ export const AddressWrapper = ( {
addressForm: JSX.Element;
shouldAnimate?: boolean;
} ): JSX.Element => {
+ const ref = useRef< HTMLDivElement >( null );
+ const wasEditingRef = useRef( isEditing );
+ useLayoutEffect( () => {
+ const card = ref.current?.firstElementChild as HTMLElement | null;
+ if ( isEditing && ! wasEditingRef.current && shouldAnimate && card ) {
+ // The card is out of the flow now, but still has the height that the wrapper had.
+ animateCollapse( ref.current, true, true, {
+ height: `${ card.offsetHeight }px`,
+ } );
+ }
+ wasEditingRef.current = isEditing;
+ }, [ isEditing, shouldAnimate ] );
+
const wrapperClasses = clsx(
'wc-block-components-address-address-wrapper',
{
@@ -32,7 +47,7 @@ export const AddressWrapper = ( {
);
return (
- <div className={ wrapperClasses }>
+ <div className={ wrapperClasses } ref={ ref }>
<div className="wc-block-components-address-card-wrapper">
{ addressCard }
</div>
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/style.scss b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/style.scss
index 395a370f2f2..44498fef070 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/style.scss
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/address-wrapper/style.scss
@@ -49,3 +49,8 @@
}
}
}
+
+// The height changes while the card and the form crossfade.
+:where(.wp-block-woocommerce-checkout) .wc-block-components-address-address-wrapper {
+ @include motion-collapse;
+}
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-billing-address-block/customer-address.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-billing-address-block/customer-address.tsx
index 3b4797211ef..47feb0181da 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-billing-address-block/customer-address.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-billing-address-block/customer-address.tsx
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
-import { useCallback, useEffect } from '@wordpress/element';
+import { useCallback, useEffect, useState } from '@wordpress/element';
import { Form } from '@woocommerce/base-components/cart-checkout';
import {
useCheckoutAddress,
@@ -12,6 +12,7 @@ import type { AddressFormValues } from '@woocommerce/settings';
import { useSelect } from '@wordpress/data';
import { validationStore } from '@woocommerce/block-data';
import { ADDRESS_FORM_KEYS } from '@woocommerce/block-settings';
+import type { MouseEvent } from 'react';
/**
* Internal dependencies
@@ -30,6 +31,7 @@ const CustomerAddress = () => {
} = useCheckoutAddress();
const { dispatchCheckoutEvent } = useStoreEvents();
const { isInitialized } = useCustomerData();
+ const [ shouldAnimate, setShouldAnimate ] = useState( false );
const { validationErrors } = useSelect(
( select ) => {
@@ -87,11 +89,14 @@ const CustomerAddress = () => {
return (
<AddressWrapper
isEditing={ editingBillingAddress }
+ shouldAnimate={ shouldAnimate }
addressCard={
<AddressCard
address={ billingAddress }
target="billing"
- onEdit={ () => {
+ onEdit={ ( event: MouseEvent ) => {
+ // A click that a key press starts has no click count, and applies immediately.
+ setShouldAnimate( event.detail !== 0 );
setEditingBillingAddress( true );
} }
isExpanded={ editingBillingAddress }
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 d90a71f9310..c265ae758ab 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
@@ -98,3 +98,11 @@
text-decoration: underline;
}
}
+
+// The billing section and the address line 2 field grow in, and the billing section collapses out.
+:where(.wp-block-woocommerce-checkout) {
+ .wc-block-checkout__billing-fields,
+ .wc-block-components-address-form__address_2 {
+ @include motion-collapse;
+ }
+}
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx
index 11bebd556c4..c44b04cb387 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx
@@ -16,6 +16,7 @@ import Noninteractive from '@woocommerce/base-components/noninteractive';
import type { BillingAddress } from '@woocommerce/settings';
import { getSetting } from '@woocommerce/settings';
import { emptyAddressFields } from '@woocommerce/base-utils';
+import { useToggleCollapse } from '@woocommerce/base-hooks';
import type { CartResponseBillingAddress } from '@woocommerce/types';
/**
@@ -86,6 +87,11 @@ const Block = (): JSX.Element => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [] );
+ // The checkbox collapses the billing section out and grows it in.
+ const billingCollapse = useToggleCollapse( ! useShippingAsBilling, () =>
+ document.getElementById( 'billing-fields' )
+ );
+
const WrapperComponent = isEditor ? Noninteractive : Fragment;
const noticeContext = useShippingAsBilling
? [ noticeContexts.SHIPPING_ADDRESS, noticeContexts.BILLING_ADDRESS ]
@@ -98,10 +104,12 @@ const Block = (): JSX.Element => {
<CustomerAddress />
</WrapperComponent>
<CheckboxControl
+ ref={ billingCollapse.triggerRef }
className="wc-block-checkout__use-address-for-billing"
label={ __( 'Use same address for billing', 'woocommerce' ) }
checked={ useShippingAsBilling }
onChange={ ( checked: boolean ) => {
+ billingCollapse.onToggle();
setUseShippingAsBilling( checked );
if ( checked ) {
syncBillingWithShipping();
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx
index 4749d57e2b1..99869aad409 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx
@@ -12,6 +12,7 @@ import type { ShippingAddress } from '@woocommerce/settings';
import { useSelect } from '@wordpress/data';
import { validationStore } from '@woocommerce/block-data';
import { ADDRESS_FORM_KEYS } from '@woocommerce/block-settings';
+import type { MouseEvent } from 'react';
/**
* Internal dependencies
@@ -86,10 +87,14 @@ const CustomerAddress = () => {
]
);
- const handleEditClick = useCallback( () => {
- setShouldAnimate( true );
- setEditingShippingAddress( true );
- }, [ setEditingShippingAddress ] );
+ const handleEditClick = useCallback(
+ ( event: MouseEvent ) => {
+ // A click that a key press starts has no click count, and applies immediately.
+ setShouldAnimate( event.detail !== 0 );
+ setEditingShippingAddress( true );
+ },
+ [ setEditingShippingAddress ]
+ );
return (
<AddressWrapper
diff --git a/plugins/woocommerce/client/blocks/docs/contributors/motion.md b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
index d8fdad2ed42..45045d02325 100644
--- a/plugins/woocommerce/client/blocks/docs/contributors/motion.md
+++ b/plugins/woocommerce/client/blocks/docs/contributors/motion.md
@@ -93,7 +93,9 @@ Motion that changes the layout runs in JavaScript, because it must measure sizes
|--------|-----|
| `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, { 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`. |
+| `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. |
+| `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. |
## Techniques
@@ -112,6 +114,7 @@ Find the change in this table, and use the helpers above.
| A dropdown opens from a field | It slides 4px from the field and fades in. It slides back to close. |
| A toast or snackbar appears and goes | It rises in and drops out. |
| Content appears or goes and moves the content below, such as a panel, notice, field error, or section | It grows and collapses in the real layout. It stays mounted while it goes. |
+| A form or its fields go | The real form unmounts at once, so its fields stop counting. An inert copy collapses in its place. |
| 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. |