From 8339ecc5f15fb8390d1f34863ce9eb095bc8f63a Mon Sep 17 00:00:00 2001 From: Alex Andreev Date: Tue, 9 Mar 2021 12:06:39 +0300 Subject: [PATCH] Updating navigation on DOM mutations Signed-off-by: Alex Andreev --- .../components/scroll-spy/scroll-spy.tsx | 4 +-- src/renderer/hooks/index.ts | 1 + src/renderer/hooks/useMutationObserver.ts | 26 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 src/renderer/hooks/useMutationObserver.ts 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]); +}