diff --git a/src/renderer/components/scroll-spy/scroll-spy.tsx b/src/renderer/components/scroll-spy/scroll-spy.tsx index 62eac57701..6edfc13647 100644 --- a/src/renderer/components/scroll-spy/scroll-spy.tsx +++ b/src/renderer/components/scroll-spy/scroll-spy.tsx @@ -1,4 +1,5 @@ import React, { useEffect, useRef, useState } from "react"; +import { useMutationObserver } from "../../hooks"; import { NavigationTree } from "../tree-view"; interface Props extends React.DOMAttributes { @@ -75,14 +76,13 @@ export function ScrollSpy(props: Props) { useEffect(() => { setSections(); observeSections(); - // TODO: Attach on dom change event }, []); useEffect(() => { updateNavigation(); }, [activeElementId]); - console.log(activeElementId); + useMutationObserver(parent, updateNavigation); return (
diff --git a/src/renderer/hooks/index.ts b/src/renderer/hooks/index.ts index 860847e979..3d94196ac0 100644 --- a/src/renderer/hooks/index.ts +++ b/src/renderer/hooks/index.ts @@ -3,3 +3,4 @@ export * from "./useStorage"; export * from "./useOnUnmount"; export * from "./useInterval"; +export * from "./useMutationObserver"; diff --git a/src/renderer/hooks/useMutationObserver.ts b/src/renderer/hooks/useMutationObserver.ts new file mode 100644 index 0000000000..e08999ab9b --- /dev/null +++ b/src/renderer/hooks/useMutationObserver.ts @@ -0,0 +1,26 @@ +import { MutableRefObject, useEffect } from "react"; + +const config: MutationObserverInit = { + subtree: true, + childList: true, + attributes: false, + characterData: false +}; + +export function useMutationObserver( + ref: MutableRefObject, + callback: MutationCallback, + options: MutationObserverInit = config +) { + useEffect(() => { + if (ref.current) { + const observer = new MutationObserver(callback); + + observer.observe(ref.current, options); + + return () => { + observer.disconnect(); + }; + } + }, [callback, options]); +}