|
| 1 | +import * as React from "react"; |
| 2 | +import { |
| 3 | + MutableRefObject, |
| 4 | + ReactNode, |
| 5 | + useEffect, |
| 6 | + useRef, |
| 7 | + useState, |
| 8 | +} from "react"; |
| 9 | +import { isVisible } from "../utils/isVisible"; |
| 10 | +import { throttle } from "../utils/throttle"; |
| 11 | + |
| 12 | +interface ScrollSpyProps { |
| 13 | + children: ReactNode; |
| 14 | + navContainerRef?: MutableRefObject<HTMLDivElement | null>; |
| 15 | + scrollThrottle?: number; |
| 16 | +} |
| 17 | + |
| 18 | +const ScrollSpy = ({ |
| 19 | + children, |
| 20 | + navContainerRef, |
| 21 | + scrollThrottle = 300, |
| 22 | +}: ScrollSpyProps) => { |
| 23 | + const scrollContainerRef = useRef<HTMLDivElement | null>(null); |
| 24 | + const [navContainerItems, setNavContainerItems] = useState<NodeListOf<Element> | undefined>(); // prettier-ignore |
| 25 | + |
| 26 | + // keeps track of the Id in navcontainer which is active |
| 27 | + // so as to not update classLists unless it has been updated |
| 28 | + const prevIdTracker = useRef(""); |
| 29 | + |
| 30 | + // To get the nav container items depending on whether the parent ref for the nav container is passed or not |
| 31 | + useEffect(() => { |
| 32 | + if (navContainerRef) { |
| 33 | + setNavContainerItems( |
| 34 | + navContainerRef.current?.querySelectorAll("[data-to-scrollspy-id]") |
| 35 | + ); |
| 36 | + } else { |
| 37 | + setNavContainerItems(document.querySelectorAll("[data-to-scrollspy-id]")); |
| 38 | + } |
| 39 | + |
| 40 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 41 | + }, [navContainerRef]); |
| 42 | + |
| 43 | + // fire once after nav container items are set |
| 44 | + useEffect(() => { |
| 45 | + checkAndUpdateActiveScrollSpy(); |
| 46 | + |
| 47 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 48 | + }, [navContainerItems]); |
| 49 | + |
| 50 | + const checkAndUpdateActiveScrollSpy = () => { |
| 51 | + const scrollParentContainer = scrollContainerRef.current; |
| 52 | + |
| 53 | + // if there are no children, return |
| 54 | + if (!(scrollParentContainer && navContainerItems)) return; |
| 55 | + |
| 56 | + // loop over all children in scroll container |
| 57 | + for (let i = 0; i < scrollParentContainer.children.length; i++) { |
| 58 | + // get child element |
| 59 | + const child = scrollParentContainer.children.item(i); |
| 60 | + if (!child) continue; |
| 61 | + const useChild = child as HTMLDivElement; |
| 62 | + |
| 63 | + // check if the element is in the viewport |
| 64 | + if (isVisible(useChild)) { |
| 65 | + // if so, get its ID |
| 66 | + const changeHighlightedItemId = useChild.id; |
| 67 | + |
| 68 | + // if the element was same as the one currently active ignore it |
| 69 | + if (prevIdTracker.current === changeHighlightedItemId) return; |
| 70 | + |
| 71 | + // now loop over each element in the nav Container |
| 72 | + navContainerItems.forEach((el) => { |
| 73 | + const attrId = el.getAttribute("data-to-scrollspy-id"); |
| 74 | + |
| 75 | + // if the element contains 'active' the class remove it |
| 76 | + if (el.classList.contains("active-scroll-spy")) { |
| 77 | + el.classList.remove("active-scroll-spy"); |
| 78 | + } |
| 79 | + |
| 80 | + // check if its ID matches the ID we got from the viewport |
| 81 | + // also make sure it does not already contain the 'active' class |
| 82 | + if ( |
| 83 | + attrId === changeHighlightedItemId && |
| 84 | + !el.classList.contains("active-scroll-spy") |
| 85 | + ) { |
| 86 | + el.classList.add("active-scroll-spy"); |
| 87 | + |
| 88 | + console.log("update to", changeHighlightedItemId); |
| 89 | + prevIdTracker.current = changeHighlightedItemId; |
| 90 | + window.history.pushState({}, "", `#${changeHighlightedItemId}`); |
| 91 | + } |
| 92 | + }); |
| 93 | + break; |
| 94 | + } |
| 95 | + } |
| 96 | + }; |
| 97 | + |
| 98 | + window.addEventListener( |
| 99 | + "scroll", |
| 100 | + throttle(checkAndUpdateActiveScrollSpy, scrollThrottle) |
| 101 | + ); |
| 102 | + |
| 103 | + return <div ref={scrollContainerRef}>{children}</div>; |
| 104 | +}; |
| 105 | + |
| 106 | +export default ScrollSpy; |
0 commit comments