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 18, 2022
1 parent 3c6609b commit eb2ab13
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions packages/components/src/popover/index.js
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 @@ -310,6 +313,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 eb2ab13

Please sign in to comment.