1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Fine-tuning IntersectionObserver options

Signed-off-by: Alex Andreev <alex.andreev.email@gmail.com>
This commit is contained in:
Alex Andreev 2021-03-04 14:17:37 +03:00
parent a2bb733e48
commit 06e747dfa8

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { NavigationTree } from "../tree-view"; import { NavigationTree } from "../tree-view";
interface Props extends React.DOMAttributes<any> { interface Props extends React.DOMAttributes<any> {
@ -6,23 +6,23 @@ interface Props extends React.DOMAttributes<any> {
} }
export function ScrollSpy(props: Props) { export function ScrollSpy(props: Props) {
const parent = useRef<HTMLDivElement>();
const sections = useRef<NodeListOf<HTMLElement>>();
const [tree, setTree] = useState<NavigationTree[]>([]); const [tree, setTree] = useState<NavigationTree[]>([]);
const [activeElementId, setActiveElementId] = useState(""); const [activeElementId, setActiveElementId] = useState("");
const getContentParentElement = () => { const setSections = () => {
const firstSection = document.querySelector("section"); sections.current = parent.current.querySelectorAll("section");
if (!firstSection) { if (!sections.current.length) {
throw new Error("No <section/> tag founded! Content should be placed inside <section></section> elements to activate navigation."); throw new Error("No <section/> tag founded! Content should be placed inside <section></section> elements to activate navigation.");
} }
return firstSection.parentElement;
}; };
const updateNavigation = () => { const updateNavigation = () => {
setTree([ setTree([
...tree, ...tree,
...getNavigation(getContentParentElement()) ...getNavigation(sections.current[0].parentElement)
]); ]);
}; };
@ -55,12 +55,12 @@ export function ScrollSpy(props: Props) {
}; };
const observeSections = () => { const observeSections = () => {
const sections = getContentParentElement().querySelectorAll("section"); const options: IntersectionObserverInit = {
const options = { threshold: [0],
rootMargin: "-50% 0px" rootMargin: "0px 0px -85%",
}; };
sections.forEach((section) => { sections.current.forEach((section) => {
const observer = new IntersectionObserver(handleIntersect, options); const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(section); observer.observe(section);
@ -68,14 +68,16 @@ export function ScrollSpy(props: Props) {
}; };
useEffect(() => { useEffect(() => {
updateNavigation(); setSections();
observeSections(); observeSections();
// element.current.addEventListener("scroll", updateActive); updateNavigation();
// TODO: Attach on dom change event // TODO: Attach on dom change event
}, []); }, []);
console.log(activeElementId);
return ( return (
<div className="ScrollSpy"> <div className="ScrollSpy" ref={parent}>
{props.render(tree)} {props.render(tree)}
</div> </div>
); );