"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useScroll = useScroll; var _react = require("react"); var _lodash = _interopRequireDefault(require("lodash")); var _constants = require("../../common/constants"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ const SCROLL_END_BUFFER_HEIGHT = 20; function getScrollPosition(div) { if (div) { return div.scrollTop; } else { return document.documentElement.scrollTop || document.body.scrollTop; } } /** * listens to scroll events on given div, if scroll reaches bottom, calls a callback * @param {ref} ref to listen to scroll events on * @param {function} handler function receives params (scrollTop, endReached) */ function useScroll({ div, handler }) { (0, _react.useEffect)(() => { if (div) { const debounced = _lodash.default.debounce(() => { const pos = getScrollPosition(div); const endReached = pos + div.offsetHeight > div.scrollHeight - SCROLL_END_BUFFER_HEIGHT; handler(pos, endReached); }, _constants.DEBOUNCE_TIMEOUT); div.onscroll = debounced; return () => { debounced.cancel(); div.onscroll = null; }; } }, [div, handler]); }