"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useVisible = useVisible; var _react = require("react"); var _lodash = 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. */ /** * Check if an element is in viewport * @param {HTMLDivElement} viewPortEl - View port element of where the scroll takes place * @param {function} visibleCallback - callback called onScroll, expects (isVisbile: boolean, isAbove: boolean) as params * @param {boolean} shouldAddListener - if useVisible hook should add the scroll listener * @param {number} offset - Number of pixels up to the observable element from the top * @param {number} debounceTimeout - debounce timeout, in ms */ function useVisible({ viewPortEl, visibleCallback, shouldAddListener = false, offset = 0, debounceTimeout = _constants.DEBOUNCE_TIMEOUT }) { const currentElement = (0, _react.useRef)(null); const onScroll = (0, _react.useMemo)(() => (0, _lodash.debounce)(() => { if (!currentElement.current || !viewPortEl) { return; } const { height: elHeight, y: elTop } = currentElement.current.getBoundingClientRect(); const { y: viewPortElTop } = viewPortEl.getBoundingClientRect(); const viewPortElBottom = viewPortElTop + viewPortEl.clientHeight; const elBottom = elTop + elHeight; const isVisible = elBottom + offset >= viewPortElTop && elTop - offset <= viewPortElBottom; // if elBottom + offset < viewPortElTop, the currentElement is above the current scroll window visibleCallback(isVisible, elBottom + offset < viewPortElTop); }, debounceTimeout), [debounceTimeout, offset, viewPortEl, visibleCallback]); (0, _react.useEffect)(() => { if (shouldAddListener) { viewPortEl === null || viewPortEl === void 0 ? void 0 : viewPortEl.addEventListener('scroll', onScroll); } return () => { if (shouldAddListener) { viewPortEl === null || viewPortEl === void 0 ? void 0 : viewPortEl.removeEventListener('scroll', onScroll); } }; }, [onScroll, viewPortEl, shouldAddListener]); return currentElement; }