From 06e747dfa8f65b06c747ccd1dd436c0e5bbc0338 Mon Sep 17 00:00:00 2001 From: Alex Andreev Date: Thu, 4 Mar 2021 14:17:37 +0300 Subject: [PATCH] Fine-tuning IntersectionObserver options Signed-off-by: Alex Andreev --- .../components/scroll-spy/scroll-spy.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/renderer/components/scroll-spy/scroll-spy.tsx b/src/renderer/components/scroll-spy/scroll-spy.tsx index 895d8af5ed..223276f436 100644 --- a/src/renderer/components/scroll-spy/scroll-spy.tsx +++ b/src/renderer/components/scroll-spy/scroll-spy.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import { NavigationTree } from "../tree-view"; interface Props extends React.DOMAttributes { @@ -6,23 +6,23 @@ interface Props extends React.DOMAttributes { } export function ScrollSpy(props: Props) { + const parent = useRef(); + const sections = useRef>(); const [tree, setTree] = useState([]); const [activeElementId, setActiveElementId] = useState(""); - const getContentParentElement = () => { - const firstSection = document.querySelector("section"); + const setSections = () => { + sections.current = parent.current.querySelectorAll("section"); - if (!firstSection) { + if (!sections.current.length) { throw new Error("No
tag founded! Content should be placed inside
elements to activate navigation."); } - - return firstSection.parentElement; }; const updateNavigation = () => { setTree([ ...tree, - ...getNavigation(getContentParentElement()) + ...getNavigation(sections.current[0].parentElement) ]); }; @@ -55,12 +55,12 @@ export function ScrollSpy(props: Props) { }; const observeSections = () => { - const sections = getContentParentElement().querySelectorAll("section"); - const options = { - rootMargin: "-50% 0px" + const options: IntersectionObserverInit = { + threshold: [0], + rootMargin: "0px 0px -85%", }; - sections.forEach((section) => { + sections.current.forEach((section) => { const observer = new IntersectionObserver(handleIntersect, options); observer.observe(section); @@ -68,14 +68,16 @@ export function ScrollSpy(props: Props) { }; useEffect(() => { - updateNavigation(); + setSections(); observeSections(); - // element.current.addEventListener("scroll", updateActive); + updateNavigation(); // TODO: Attach on dom change event }, []); + console.log(activeElementId); + return ( -
+
{props.render(tree)}
);