UNPKG

@redocly/theme

Version:

Shared UI components lib

47 lines 2.01 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useActiveSectionId = useActiveSectionId; const react_1 = require("react"); const lodash_throttle_1 = __importDefault(require("lodash.throttle")); const use_navbar_height_1 = require("./use-navbar-height"); function useActiveSectionId(location, hasOverviewPage = false, withNavbar = true, sectionOffset = 150) { const [itemId, setItemId] = (0, react_1.useState)(''); const navbarHeight = (0, use_navbar_height_1.useNavbarHeight)(location); const heightOffset = (withNavbar ? navbarHeight : 0) + sectionOffset; const scrollListener = (0, react_1.useMemo)(() => (0, lodash_throttle_1.default)(() => { const sections = document.querySelectorAll('[data-section-id]'); if (sections.length < 2) { setItemId(''); return; } if (window.scrollY <= 0) { setItemId(sections[0].getAttribute('data-section-id') || ''); return; } for (let i = 0; i < sections.length; i++) { const section = sections[i]; const rect = section.getBoundingClientRect(); if (rect.y < heightOffset && rect.bottom > heightOffset) { setItemId(section.getAttribute('data-section-id') || ''); return; } } if (hasOverviewPage) { setItemId(''); } }, 150), [heightOffset, hasOverviewPage]); (0, react_1.useEffect)(() => { window.addEventListener('scroll', scrollListener, { capture: false }); setTimeout(() => { scrollListener(); }, 10); return () => { window.removeEventListener('scroll', scrollListener); }; }, [location, heightOffset, scrollListener]); return itemId; } //# sourceMappingURL=use-active-section-id.js.map