import * as React from "react" ; import ResizeObserver from "resize-observer-polyfill" ; import { AbstractPureComponent2 , DISPLAYNAME_PREFIX , ResizeEntry } from "@blueprintjs/core" ; /** `ResizeSensor2` requires a single DOM element child and will error otherwise. */ export interface ResizeSensor2Props { /**
     * Single child, must be an element and not a string or fragment.
     */ children : JSX . Element ; /**
     * Callback invoked when the wrapped element resizes.
     *
     * The `entries` array contains an entry for each observed element. In the
     * default case (no `observeParents`), the array will contain only one
     * element: the single child of the `ResizeSensor`.
     *
     * Note that this method is called _asynchronously_ after a resize is
     * detected and typically it will be called no more than once per frame.
     */ onResize : ( entries : ResizeEntry [ ] ) => void ; default observeParents ? : boolean ; /**
     * If you attach a `ref` to the child yourself when rendering it, you must pass the
     * same value here (otherwise, ResizeSensor won't be able to attach its own).
     */ targetRef ? : React . Ref < any > ; } export class ResizeSensor2 extends AbstractPureComponent2 < ResizeSensor2Props > { public static displayName = `${ DISPLAYNAME_PREFIX }.ResizeSensor2` ; private targetRef = React . createRef < HTMLElement > ( ) ; private prevElement : HTMLElement | undefined = undefined ; private observer = new ResizeObserver ( entries => this . props . onResize ?. ( entries ) ) ; public render ( ) { const onlyChild = React . Children . only ( this . props . children ) ; if ( this . props . targetRef !== undefined ) { return onlyChild ; } return React . cloneElement ( onlyChild , { ref : this . targetRef } ) ; } public componentDidMount ( ) { this . observeElement ( ) ; } public componentDidUpdate ( prevProps ) { this . observeElement ( this . props . observeParents !== prevProps . observeParents ) ; } public componentWillUnmount ( ) { this . observer . disconnect ( ) ; } /**
     * Observe the DOM element, if defined and different from the currently
     * observed element. Pass `force` argument to skip element checks and always
     * re-observe.
     */ private observeElement ( force = false ) { if ( ! ( this . targetRef . current instanceof Element ) ) { this . observer . disconnect ( ) ; return ; } if ( this . targetRef . current === this . prevElement && ! force ) { return ; } else { this . observer . disconnect ( ) ; this . prevElement = this . targetRef . current ; } this . observer . observe ( this . targetRef . current ) ; if ( this . props . observeParents ) { let parent = this . targetRef . current . parentElement ; while ( parent != null ) { this . observer . observe ( parent ) ; parent = parent . parentElement ; } } } }