pmndrs / react-spring

✌️ A spring physics based React animation library
http://www.react-spring.dev/
MIT License
27.73k stars 1.18k forks source link

[bug]: `useResize` uses content box instead of border box #2288

Open LoganDark opened 3 weeks ago

LoganDark commented 3 weeks ago

Which react-spring target are you using?

What version of react-spring are you using?

9.7.3

What's Wrong?

useResize returns the size of the content box, without padding or borders. It should use the border box instead.

https://github.com/pmndrs/react-spring/blob/1e4406e322f878141718737638bb6e96e717dd63/packages/shared/src/dom-events/resize/resizeElement.ts#L42-L44

-   if (observer) {
-     observer.observe(target)
-   }
+   observer?.observe(target, { box: 'border-box' })

https://github.com/pmndrs/react-spring/blob/1e4406e322f878141718737638bb6e96e717dd63/packages/shared/src/dom-events/resize/resizeElement.ts#L7-L10

 const handleObservation = (entries: ResizeObserverEntry[]) =>
-  entries.forEach(({ target, contentRect }) => {
-    return resizeHandlers.get(target)?.forEach(handler => handler(contentRect))
+  entries.forEach(({ target, borderBoxSize }) => {
+    const handlers = resizeHandlers.get(target)
+    if (!handlers) return
+    const { blockSize, inlineSize } = borderBoxSize[0]
+    const { width, height } = !getComputedStyle(target).getPropertyValue('writing-mode')?.startsWith('vertical-')
+      ? { width: inlineSize, height: blockSize }
+      : { width: blockSize, height: inlineSize }
+    for (const handler of handlers) handler({ width, height })
   })

MDN

To Reproduce

observe an element that has padding.

Expected Behaviour

padding should be included in the returned size.

Link to repo

https://codesandbox.io/p/sandbox/muddy-hill-sjfzwl