diff --git a/packages/block-editor/src/components/url-popover/test/__snapshots__/index.js.snap b/packages/block-editor/src/components/url-popover/test/__snapshots__/index.js.snap index 502c850838f46..c7ecbc209a241 100644 --- a/packages/block-editor/src/components/url-popover/test/__snapshots__/index.js.snap +++ b/packages/block-editor/src/components/url-popover/test/__snapshots__/index.js.snap @@ -5,7 +5,7 @@ exports[`URLPopover matches the snapshot in its default state 1`] = `
diff --git a/packages/components/src/popover/test/index.tsx b/packages/components/src/popover/test/index.tsx index 256b89415cfae..7fb9e5377bf31 100644 --- a/packages/components/src/popover/test/index.tsx +++ b/packages/components/src/popover/test/index.tsx @@ -12,7 +12,11 @@ import { useState } from '@wordpress/element'; /** * Internal dependencies */ -import { positionToPlacement, placementToMotionAnimationProps } from '../utils'; +import { + computePopoverPosition, + positionToPlacement, + placementToMotionAnimationProps, +} from '../utils'; import Popover from '..'; import type { PopoverProps } from '../types'; @@ -248,4 +252,21 @@ describe( 'Popover', () => { ); } ); } ); + + describe( 'computePopoverPosition', () => { + it.each( [ + [ 14, 14 ], // valid integers shouldn't be changes + [ 14.02, 14 ], // floating numbers are parsed to integers + [ 0, 0 ], // zero remains zero + [ null, undefined ], + [ NaN, undefined ], + ] )( + 'converts `%s` to `%s`', + ( inputCoordinate, expectedCoordinated ) => { + expect( computePopoverPosition( inputCoordinate ) ).toEqual( + expectedCoordinated + ); + } + ); + } ); } ); diff --git a/packages/components/src/popover/utils.ts b/packages/components/src/popover/utils.ts index 022e7796fe37d..2112b28596982 100644 --- a/packages/components/src/popover/utils.ts +++ b/packages/components/src/popover/utils.ts @@ -318,3 +318,15 @@ export const getReferenceElement = ( { // Convert any `undefined` value to `null`. return referenceElement ?? null; }; + +/** + * Computes the final coordinate that needs to be applied to the floating + * element when applying transform inline styles, defaulting to `undefined` + * if the provided value is `null` or `NaN`. + * + * @param c input coordinate (usually as returned from floating-ui) + * @return The coordinate's value to be used for inline styles. An `undefined` + * return value means "no style set" for this coordinate. + */ +export const computePopoverPosition = ( c: number | null ) => + c === null || Number.isNaN( c ) ? undefined : Math.round( c );