@redocly/theme
Version:
Shared UI components lib
43 lines • 1.86 kB
JavaScript
;
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 hooks_1 = require("../../core/hooks");
function useActiveSectionId(location, hasOverviewPage = false, withNavbar = true) {
const [itemId, setItemId] = (0, react_1.useState)('');
const navbarHeight = (0, hooks_1.useNavbarHeight)(location);
const heightOffset = (withNavbar ? navbarHeight : 0) + 150; // use 150px to account next section visibility;
const scrollListener = (0, react_1.useMemo)(() => (0, lodash_throttle_1.default)(() => {
const sections = document.querySelectorAll('[data-section-id]');
if (sections.length < 2) {
setItemId('');
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