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

Updating navigation on DOM mutations

Signed-off-by: Alex Andreev <alex.andreev.email@gmail.com>
This commit is contained in:
Alex Andreev 2021-03-09 12:06:39 +03:00
parent 09a009049f
commit 8339ecc5f1
3 changed files with 29 additions and 2 deletions

View File

@ -1,4 +1,5 @@
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { useMutationObserver } from "../../hooks";
import { NavigationTree } from "../tree-view"; import { NavigationTree } from "../tree-view";
interface Props extends React.DOMAttributes<HTMLElement> { interface Props extends React.DOMAttributes<HTMLElement> {
@ -75,14 +76,13 @@ export function ScrollSpy(props: Props) {
useEffect(() => { useEffect(() => {
setSections(); setSections();
observeSections(); observeSections();
// TODO: Attach on dom change event
}, []); }, []);
useEffect(() => { useEffect(() => {
updateNavigation(); updateNavigation();
}, [activeElementId]); }, [activeElementId]);
console.log(activeElementId); useMutationObserver(parent, updateNavigation);
return ( return (
<div className="ScrollSpy" ref={parent}> <div className="ScrollSpy" ref={parent}>

View File

@ -3,3 +3,4 @@
export * from "./useStorage"; export * from "./useStorage";
export * from "./useOnUnmount"; export * from "./useOnUnmount";
export * from "./useInterval"; export * from "./useInterval";
export * from "./useMutationObserver";

View File

@ -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<HTMLElement>,
callback: MutationCallback,
options: MutationObserverInit = config
) {
useEffect(() => {
if (ref.current) {
const observer = new MutationObserver(callback);
observer.observe(ref.current, options);
return () => {
observer.disconnect();
};
}
}, [callback, options]);
}