From 1c2dc13fa330fe2de05d6bfabaaf1028428e8c66 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Fri, 30 Jul 2021 12:12:49 +0100 Subject: [PATCH] factor our observer hook --- src/components/structures/SpaceHierarchy.tsx | 48 +++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/components/structures/SpaceHierarchy.tsx b/src/components/structures/SpaceHierarchy.tsx index f1f5d70fa6..f13fc7f208 100644 --- a/src/components/structures/SpaceHierarchy.tsx +++ b/src/components/structures/SpaceHierarchy.tsx @@ -365,6 +365,31 @@ export const useSpaceSummary = (space: Room): { return { loading, rooms, hierarchy, loadMore }; }; +const useIntersectionObserver = (callback: () => void) => { + const handleObserver = (entries: IntersectionObserverEntry[]) => { + const target = entries[0]; + if (target.isIntersecting) { + callback(); + } + }; + + const observerRef = useRef(); + return (element: HTMLDivElement) => { + if (observerRef.current) { + observerRef.current.disconnect(); + } else if (element) { + observerRef.current = new IntersectionObserver(handleObserver, { + root: element.parentElement, + rootMargin: "0px 0px 600px 0px", + }); + } + + if (observerRef.current && element) { + observerRef.current.observe(element); + } + }; +}; + const SpaceHierarchy = ({ space, initialText = "", @@ -408,28 +433,7 @@ const SpaceHierarchy = ({ const [removing, setRemoving] = useState(false); const [saving, setSaving] = useState(false); - const handleObserver = (entries: IntersectionObserverEntry[]) => { - const target = entries[0]; - if (target.isIntersecting) { - loadMore(); - } - }; - - const observerRef = useRef(); - const loaderRef = (element: HTMLDivElement) => { - if (observerRef.current) { - observerRef.current.disconnect(); - } else if (element) { - observerRef.current = new IntersectionObserver(handleObserver, { - root: element.parentElement, - rootMargin: "0px 0px 600px 0px", - }); - } - - if (observerRef.current && element) { - observerRef.current.observe(element); - } - }; + const loaderRef = useIntersectionObserver(loadMore); if (!loading && hierarchy.noSupport) { return

{ _t("Your server does not support showing space hierarchies.") }

;