react-grid-layout / react-draggable

React draggable component
MIT License
9.04k stars 1.03k forks source link

Fix bounds="selector" functionality when in a Shadow DOM tree. #763

Open miguelcalderon opened 2 months ago

miguelcalderon commented 2 months ago

Hi! I'm Miguel Calderón and work at PSPDFKit. I'd like to say thanks for your package, which is great!

We've recently switched our SDK container from Iframe to Shadow DOM, and are about to upgrade to React 18, which is bringing up lots of small headaches, mostly caused by our own tech debt.

One of the problems we're finding is using react-draggable from within the Shadow DOM when setting the bounds prop to a selector.

Details

The bounds prop was not working correctly when set to a selector within a Shadow DOM tree. The reason is that the provided selector was being queried to ownerDocument and would throw if the node was attached within a Shadow root.

Here's an example showing the problem: https://playcode.io/1996274

The solution applied in this PR is to query the node returned by node.getRootNode() instead: this method returns ownerDocument when called on the normal DOM as before, but when the node is inside a Shadow root, the shadow root will be returned instead. Additionally, if the node is inside a fragment and not attached to a document nor a Shadow root, the topmost element will be returned.

Some tests have been added as well to cover bounds as parent as selector, from within a Shadow root and in the normal DOM.