UNPKG

react-scroll-agent

Version:

Deadly spy for make benefit glorious nation of Scrolltopia

316 lines (253 loc) 8.84 kB
import React from 'react'; import observeRect from '@reach/observe-rect'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var REFIRE = 500; var TOP = 'top'; var CENTER = 'center'; var BOTTOM = 'bottom'; var ScrollAgent = function (_React$PureComponent) { _inherits(ScrollAgent, _React$PureComponent); function ScrollAgent() { var _getPrototypeOf2; var _this; _classCallCheck(this, ScrollAgent); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(ScrollAgent)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_lastH", -1); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_lastRecalc", undefined); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "wrapper", React.createRef()); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "observer", undefined); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", { current: -1, positions: [] }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "observe", function () { if (_this.observer || !_this.wrapper.current) return; _this.observer = observeRect(_this.wrapper.current, _this.handleChange); _this.observer.observe(); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleChange", function (_ref) { var top = _ref.top, height = _ref.height; if (typeof window === 'undefined') return; _this.handleScroll(top); if (!_this.wrapper.current) return; if (height > 0 && height !== _this._lastH) { _this.handleRecalc(); _this._lastH = height; clearTimeout(_this._lastRecalc); _this._lastRecalc = setTimeout(function () { return _this.handleRecalc(); }, REFIRE); } }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleRecalc", function () { var elements = []; try { elements = _this.wrapper.current.querySelectorAll(_this.props.selector); } catch (err) { console.error("\u26A0\uFE0F ReactScrollAgent: failed prop `selector=\"".concat(_this.props.selector, "\"`. Must be a valid param for document.querySelectorAll(): https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll")); console.error(err); } _this.setState({ positions: _toConsumableArray(elements).map(function (node) { return node.getBoundingClientRect().top + window.scrollY; }).sort(function (a, b) { return a - b; }) }); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleScroll", function (top) { if (_this.props.detectEnd && Math.floor(_this._lastH - window.scrollY - window.innerHeight) <= 1) { _this.setState(function (_ref2) { var positions = _ref2.positions; return { current: positions.length - 1 }; }); return; } _this.setState(function (_ref3) { var positions = _ref3.positions; return { current: _toConsumableArray(positions).concat([Infinity]).findIndex(function (y) { return y - window.scrollY - _this.threshold > 0; }) - 1 }; }); _this._lastY = top; }); return _this; } _createClass(ScrollAgent, [{ key: "componentDidMount", value: function componentDidMount() { this.observe(); this.handleRecalc(); this.handleScroll(window.scrollY); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.observe(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.observer) this.observer.unobserve(); } }, { key: "render", value: function render() { var _this$props = this.props, children = _this$props.children, detectEnd = _this$props.detectEnd, nav = _this$props.nav, selector = _this$props.selector, threshold = _this$props.threshold, props = _objectWithoutProperties(_this$props, ["children", "detectEnd", "nav", "selector", "threshold"]); return React.createElement("div", props, nav({ current: this.state.current, positions: this.state.positions }), React.createElement("div", { ref: this.wrapper }, children)); } }, { key: "threshold", get: function get() { switch (this.props.threshold) { case CENTER: return Math.floor(window.innerHeight / 2); case BOTTOM: return window.innerHeight; case TOP: default: return 0; } } }]); return ScrollAgent; }(React.PureComponent); ScrollAgent.defaultProps = { children: undefined, detectEnd: true, nav: function nav() { return null; }, threshold: TOP }; export default ScrollAgent;