Skip to content

Commit

Permalink
Offset prop as ref, prop default value
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Aug 18, 2022
1 parent 0fb7d80 commit 4bf6dfc
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/components/src/popover/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
createContext,
useContext,
useMemo,
useEffect,
} from '@wordpress/element';
import {
useViewportMatch,
Expand Down Expand Up @@ -134,7 +135,7 @@ const Popover = (
isAlternate,
position,
placement: placementProp = 'bottom-start',
offset,
offset: offsetProp = 0,
focusOnMount = 'firstElement',
anchorRef,
anchorRect,
Expand Down Expand Up @@ -195,12 +196,17 @@ const Popover = (
* Store the offset in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const frameOffsetRef = useRef();
const frameOffsetRef = useRef( getFrameOffset( referenceOwnerDocument ) );
/**
* Store the offset prop in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const offsetRef = useRef( offsetProp );

const middleware = [
offsetMiddleware( ( { placement: currentPlacement } ) => {
if ( ! frameOffsetRef.current ) {
return offset ?? 0;
return offsetRef.current;
}

const isTopBottomPlacement =
Expand All @@ -219,11 +225,10 @@ const Popover = (
currentPlacement.includes( 'top' ) ||
currentPlacement.includes( 'left' );
const mainAxisModifier = hasBeforePlacement ? -1 : 1;
const normalizedOffset = offset ? offset : 0;

return {
mainAxis:
normalizedOffset +
offsetRef.current +
frameOffsetRef.current[ mainAxis ] * mainAxisModifier,
crossAxis: frameOffsetRef.current[ crossAxis ],
};
Expand Down Expand Up @@ -291,6 +296,11 @@ const Popover = (
middlewareData: { arrow: arrowData = {} },
} = useFloating( { placement: normalizedPlacementFromProps, middleware } );

useEffect( () => {
offsetRef.current = offsetProp;
update();
}, [ offsetProp, update ] );

// Update the `reference`'s ref.
//
// In floating-ui's terms:
Expand Down

0 comments on commit 4bf6dfc

Please sign in to comment.