-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1b3e4ac
commit b91cc18
Showing
2 changed files
with
66 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
packages/block-library/src/image/use-max-width-observer.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { cloneElement, useRef, useMemo } from '@wordpress/element'; | ||
import { useResizeObserver } from '@wordpress/compose'; | ||
|
||
function useMaxWidthObserver() { | ||
const [ contentResizeListener, { width } ] = useResizeObserver(); | ||
const observerRef = useRef(); | ||
|
||
const maxWidthObserver = ( | ||
<div | ||
// Some themes set max-width on blocks. | ||
className="wp-block" | ||
aria-hidden="true" | ||
style={ { | ||
position: 'absolute', | ||
inset: 0, | ||
width: '100%', | ||
height: 0, | ||
margin: 0, | ||
} } | ||
ref={ observerRef } | ||
> | ||
{ cloneElement( contentResizeListener, { | ||
style: { | ||
...contentResizeListener.props.style, | ||
position: 'relative', | ||
}, | ||
} ) } | ||
</div> | ||
); | ||
|
||
const maxWidth = useMemo( () => { | ||
const observer = observerRef.current; | ||
if ( ! observer ) { | ||
return width; | ||
} | ||
|
||
const win = observer.ownerDocument.defaultView; | ||
const observerStyle = win.getComputedStyle( observer ); | ||
const parentStyle = win.getComputedStyle( observer.parentElement ); | ||
|
||
const isParentBorderBox = parentStyle.boxSizing === 'border-box'; | ||
const paddingInline = isParentBorderBox | ||
? 0 | ||
: parseFloat( parentStyle.paddingLeft ) + | ||
parseFloat( parentStyle.paddingRight ); | ||
|
||
const observerMaxWidth = parseFloat( observerStyle.maxWidth ); | ||
const contentWidth = | ||
width - ( Number.isNaN( paddingInline ) ? 0 : paddingInline ); | ||
|
||
return Number.isNaN( observerMaxWidth ) | ||
? contentWidth | ||
: Math.min( contentWidth, observerMaxWidth ); | ||
}, [ width ] ); | ||
|
||
return [ maxWidthObserver, maxWidth ]; | ||
} | ||
|
||
export { useMaxWidthObserver }; |