|
| 1 | +import { useState, useEffect } from "react"; |
| 2 | +import throttle from "lodash.throttle"; |
| 3 | +/** |
| 4 | + * Tracks the given element ids and returns the active section |
| 5 | + * @param elementIds |
| 6 | + * @returns the index of the selected id in the array |
| 7 | + */ |
| 8 | +export const useSimplyScrollSpy = (elementIds: string[]) => { |
| 9 | + const [activeSection, setActiveSection] = useState(() => { |
| 10 | + const currentHash = location.hash; |
| 11 | + const targetIndex = currentHash |
| 12 | + ? elementIds.findIndex((id) => `#${id}` === currentHash) |
| 13 | + : undefined; |
| 14 | + |
| 15 | + if (targetIndex && targetIndex > 0) { |
| 16 | + return targetIndex; |
| 17 | + } |
| 18 | + return 0; |
| 19 | + }); |
| 20 | + |
| 21 | + // Sync the URL hash |
| 22 | + useEffect(() => { |
| 23 | + const currentHash = location.hash; |
| 24 | + const sectionHash = `#${elementIds[activeSection]}`; |
| 25 | + // If we have the updated hash just ignore |
| 26 | + if (currentHash === sectionHash) { |
| 27 | + return; |
| 28 | + } |
| 29 | + history.pushState(undefined, "", sectionHash); |
| 30 | + }, [activeSection]); |
| 31 | + |
| 32 | + const handle = throttle(() => { |
| 33 | + let currentSectionId = activeSection; |
| 34 | + const sectionElements: HTMLElement[] = []; |
| 35 | + for (const id of elementIds) { |
| 36 | + const ele = document.getElementById(id); |
| 37 | + if (ele) { |
| 38 | + sectionElements.push(ele); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + for (let i = 0; i < sectionElements.length; i++) { |
| 43 | + const section = sectionElements[i]; |
| 44 | + // Needs to be a valid DOM Element |
| 45 | + if (!section || !(section instanceof Element)) continue; |
| 46 | + // GetBoundingClientRect returns values relative to viewport |
| 47 | + if (section.getBoundingClientRect().top + -80 < 0) { |
| 48 | + currentSectionId = i; |
| 49 | + continue; |
| 50 | + } |
| 51 | + // No need to continue loop, if last element has been detected |
| 52 | + break; |
| 53 | + } |
| 54 | + |
| 55 | + setActiveSection(currentSectionId); |
| 56 | + }, 100); |
| 57 | + |
| 58 | + useEffect(() => { |
| 59 | + window.addEventListener("scroll", handle); |
| 60 | + |
| 61 | + // Run initially |
| 62 | + handle(); |
| 63 | + |
| 64 | + return () => { |
| 65 | + window.removeEventListener("scroll", handle); |
| 66 | + }; |
| 67 | + }, [elementIds]); |
| 68 | + |
| 69 | + return activeSection; |
| 70 | +}; |
0 commit comments