UNPKG

react-resize-reporter

Version:

Lightweight React Component that reports width and height changes when its parent resizes.

96 lines 3.63 kB
import React, { PureComponent } from 'react'; import { checkParent } from './check-parent'; const containerStyles = { overflow: 'hidden', position: 'absolute', zIndex: -1000, top: '0', right: '0', width: '100%', height: '100%', opacity: 0, pointerEvents: 'none' }; /** * HTML <object> version of the resize reporter */ export class ResizeReporter extends PureComponent { constructor() { super(...arguments); this.lastWidth = -1; this.lastHeight = -1; this.onLoad = (e) => { if (process.env.NODE_ENV !== 'production') { checkParent(e.currentTarget.parentElement); } // clean up if there is a previous element this.cleanUp(); this.$container = e.currentTarget; const win = e.currentTarget.contentDocument && e.currentTarget.contentDocument.defaultView; if (win) { win.addEventListener('resize', this.onResize); } if (this.props.reportInit) { this.checkSize(); } else { const rect = e.currentTarget.getBoundingClientRect(); this.lastWidth = rect.width; this.lastHeight = rect.height; } }; this.checkSize = () => { if (this.$container) { const newRect = this.$container.getBoundingClientRect(); const { width: newWidth, height: newHeight } = newRect; if (this.props.onSizeChanged) { if (newWidth !== this.lastWidth || newHeight !== this.lastHeight) { this.props.onSizeChanged(newWidth, newHeight, newRect); } } if (this.props.onWidthChanged && newWidth !== this.lastWidth) { this.props.onWidthChanged(newWidth, newRect); } if (this.props.onHeightChanged && newHeight !== this.lastHeight) { this.props.onHeightChanged(newHeight, newRect); } this.lastWidth = newWidth; this.lastHeight = newHeight; } }; this.onResize = () => { if (this._debounceTicket) { window.clearTimeout(this._debounceTicket); this._debounceTicket = null; } if (this.props.debounce) { this._debounceTicket = window.setTimeout(this.checkSize, this.props.debounce); } else { this.checkSize(); } }; this.cleanUp = () => { if (this._debounceTicket) { window.clearTimeout(this._debounceTicket); this._debounceTicket = null; } const win = this.$container && this.$container.contentDocument && this.$container.contentDocument.defaultView; if (win) { win.removeEventListener('resize', this.onResize); } }; } componentWillUnmount() { this.cleanUp(); } render() { const { reportInit, debounce, onSizeChanged, onWidthChanged, onHeightChanged, children, ...restProps } = this.props; return (React.createElement("object", Object.assign({ "aria-hidden": true, "aria-label": "react-resize-reporter", tabIndex: -1 }, restProps, { style: containerStyles, onLoad: this.onLoad, type: "text/html", data: "about:blank" }))); } } export default ResizeReporter; //# sourceMappingURL=object.js.map