UNPKG

react-in-viewport

Version:

Track React component in viewport using Intersection Observer API

83 lines (82 loc) 2.72 kB
"use strict"; exports.__esModule = true; exports["default"] = void 0; var _react = require("react"); var _reactAspectRatio = require("react-aspect-ratio"); var _constants = require("./constants"); var _index = require("../../index"); var _jsxRuntime = require("react/jsx-runtime"); function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } var DUMMY_IMAGE_SRC = 'https://www.gstatic.com/psa/static/1.gif'; var ImageObject = /*#__PURE__*/function (_PureComponent) { _inheritsLoose(ImageObject, _PureComponent); // eslint-disable-line function ImageObject(props) { var _this; _this = _PureComponent.call(this, props) || this; _this.loadImage = function (src) { var img = new Image(); // eslint-disable-line _this.setState({ status: _constants.LOADING }); img.onload = function () { _this.setState({ src: src, status: _constants.LOADED }); }; img.alt = 'demo'; img.src = src; }; _this.getBackgroundColor = function () { var status = _this.state.status; switch (status) { case _constants.LOADING: return 'rgba(0,0,0,.32)'; case _constants.LOADED: return 'rgba(0,0,0,.50)'; case _constants.INIT: default: return 'rgba(0,0,0,.12)'; } }; _this.state = { src: DUMMY_IMAGE_SRC, status: _constants.INIT }; return _this; } var _proto = ImageObject.prototype; _proto.componentDidMount = function componentDidMount() { if (this.props.inViewport) { this.loadImage(this.props.src); } }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.props.inViewport && this.state.status === _constants.INIT) { this.loadImage(this.props.src); } }; _proto.render = function render() { return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactAspectRatio.AspectRatio, { ratio: this.props.ratio, style: { transitionDuration: '300ms', maxWidth: '400px', marginBottom: '200px', backgroundColor: this.getBackgroundColor() }, ref: this.props.forwardedRef, children: /*#__PURE__*/(0, _jsxRuntime.jsx)("img", { src: this.state.src, alt: "demo" }) }); }; return ImageObject; }(_react.PureComponent); var LazyImage = (0, _index.handleViewport)(ImageObject, {}, { disconnectOnLeave: true }); var _default = exports["default"] = LazyImage;