Skip to content

Commit

Permalink
Update position on scroll
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad committed May 27, 2022
1 parent 2ac7d28 commit 8220fed
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions packages/components/src/popover/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,26 +135,29 @@ const Popover = (
? positionToPlacement( position )
: placement;

/**
* Offsets the the position of the popover when the anchor is inside an iframe.
*/
const frameOffset = useMemo( () => {
let ownerDocument = document;
const ownerDocument = useMemo( () => {
if ( anchorRef?.top ) {
ownerDocument = anchorRef?.top.ownerDocument;
return anchorRef?.top.ownerDocument;
} else if ( anchorRef?.startContainer ) {
ownerDocument = anchorRef.startContainer.ownerDocument;
return anchorRef.startContainer.ownerDocument;
} else if ( anchorRef?.current ) {
ownerDocument = anchorRef.current.ownerDocument;
return anchorRef.current.ownerDocument;
} else if ( anchorRef ) {
// This one should be deprecated.
ownerDocument = anchorRef.ownerDocument;
return anchorRef.ownerDocument;
} else if ( anchorRect && anchorRect?.ownerDocument ) {
ownerDocument = anchorRect.ownerDocument;
return anchorRect.ownerDocument;
} else if ( getAnchorRect ) {
ownerDocument = getAnchorRect()?.ownerDocument ?? document;
return getAnchorRect()?.ownerDocument ?? document;
}

return document;
}, [ anchorRef, anchorRect, getAnchorRect ] );

/**
* Offsets the the position of the popover when the anchor is inside an iframe.
*/
const frameOffset = useMemo( () => {
const { defaultView } = ownerDocument;
const { frameElement } = defaultView;

Expand All @@ -172,7 +175,7 @@ const Popover = (
};
},
};
}, [ anchorRef, anchorRect, getAnchorRect ] );
}, [ ownerDocument ] );

const middlewares = [
frameOffset,
Expand Down Expand Up @@ -311,6 +314,16 @@ const Popover = (
};
}, [ __unstableObserveElement ] );

// If we're using getAnchorRect, we need to update the position as we scroll the iframe.
useLayoutEffect( () => {
if ( ownerDocument === document ) {
return;
}

ownerDocument.addEventListener( 'scroll', update );
return () => ownerDocument.removeEventListener( 'scroll', update );
}, [ ownerDocument ] );

/** @type {false | string} */
const animateClassName =
!! animate &&
Expand Down

0 comments on commit 8220fed

Please sign in to comment.