@shopgate/engage
Version:
Shopgate's ENGAGE library.
101 lines (98 loc) • 2.6 kB
JavaScript
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
var _IntersectionVisibility;
import { Component } from 'react';
import PropTypes from 'prop-types';
import 'intersection-observer';
/**
* The IntersectionVisibility component.
* @example
* <IntersectionVisibility>
* {({ visible, ratio, setRef }) => (
<Video autoPlay={visible && ratio > 0.8} ref={setRef} />}
)}
* </IntersectionVisibility>
*/
let IntersectionVisibility = /*#__PURE__*/function (_Component) {
/**
* Initializes the component state.
* @param {Object} props The components props.
*/
function IntersectionVisibility(props) {
var _this;
_this = _Component.call(this, props) || this;
/**
* @param {Object} ref ref
*/
_this.setRef = ref => {
if (!ref) {
return;
}
_this.node = ref;
if (_this.io) {
_this.io.observe(_this.node);
}
};
/**
* @param {IntersectionObserverEntry[]} entries first entry
*/
_this.handleIntersectionEvent = entries => {
const [{
intersectionRatio
}] = entries;
_this.setState({
visible: intersectionRatio > 0,
ratio: intersectionRatio,
entries
});
};
_this.state = {
visible: true,
ratio: 1,
entries: null
};
return _this;
}
/**
* Start the observer when the component is mounted
*/
_inheritsLoose(IntersectionVisibility, _Component);
var _proto = IntersectionVisibility.prototype;
_proto.componentDidMount = function componentDidMount() {
this.io = new IntersectionObserver(this.handleIntersectionEvent, {
threshold: this.props.thresholds
});
if (this.node) {
this.io.observe(this.node);
}
}
/**
* @inheritDoc
*/;
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.io) {
this.io.disconnect();
}
};
/**
* @returns {JSX.Element}
*/
_proto.render = function render() {
return this.props.children({
...this.state,
setRef: this.setRef
});
};
return IntersectionVisibility;
}(Component);
_IntersectionVisibility = IntersectionVisibility;
/**
* Calculate threshold by number of steps
* Ex: 5 steps will be [0.20, 0.40, 0.60, 0.80, 1.00]
* @param {number} steps .
* @returns {number[]}
*/
IntersectionVisibility.buildThresholdList = steps => Array(steps).fill(0).map((v, i) => (i + 1) / steps);
IntersectionVisibility.defaultProps = {
thresholds: _IntersectionVisibility.buildThresholdList(10)
};
export default IntersectionVisibility;