import { isWeb , useIsomorphicLayoutEffect } from '@tamagui/core' ; import { useRef , useState } from 'react' ; import { LayoutChangeEvent , LayoutRectangle } from 'react-native' ; export const useLayout = ( props = { } ) => { const [ layout , setLayout ] = useState < LayoutRectangle | null > ( null ) ; if ( ! isWeb ) { return { layout , onLayout : props . onLayout , } ; } const ref = useRef < any > ( null ) ; useIsomorphicLayoutEffect ( ( ) => { const node = ref . current ; if ( ! node ) return ; let last = null ; const getNextAndCallback = ( rect ) => { let next ; const width = Math . max ( 1 , Math . round ( rect . width ) ) ; const height = Math . max ( 1 , Math . round ( rect . height ) ) ; if ( ! last || width !== last . width || height !== last . height ) { next = { width , height } ; } if ( next ) { props . onLayout ?. ( { nativeEvent : { layout : next } } ) ; last = next ; return next ; } return last ; } ; const update = ( rect ) => { if ( props . stateless ) { getNextAndCallback ( rect ) ; } else { setLayout ( ( p ) => getNextAndCallback ( rect ) ) ; } } ; const ro = new ResizeObserver ( ( [ { contentRect } ] = [ ] ) => { update ( contentRect ) ; } ) ; ro . observe ( node ) ; return ( ) => { ro . disconnect ( ) ; } ; } , [ ref ] ) ; return { layout , ref , } ; } ;