From 969ad36def3cc0d1a82a60dc6d9f8e01e32712aa Mon Sep 17 00:00:00 2001 From: Aaron Delasy Date: Sat, 19 Oct 2024 21:10:23 +0300 Subject: [PATCH] Fix visualizer intersection observer --- components/Visualizer.tsx | 47 +++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/components/Visualizer.tsx b/components/Visualizer.tsx index 4f8bcef..0e239d1 100644 --- a/components/Visualizer.tsx +++ b/components/Visualizer.tsx @@ -30,12 +30,13 @@ export function Visualizer({ const interval = React.useRef | null>(null); const timeout = React.useRef | null>(null); const canvas = React.useRef(null); + const visible = React.useRef(false); const [running, setRunning] = React.useState(false); React.useEffect(() => { if ( - canvas.current !== null && visualizer.ready && + canvas.current !== null && renderer.current === null ) { renderer.current = new Renderer( @@ -60,9 +61,9 @@ export function Visualizer({ setRunning(true); interval.current = setInterval(() => { - // if (!running) { - // return; - // } + if (!visible.current) { + return; + } if (!simulator.current.finished()) { simulator.current.step(); @@ -95,23 +96,17 @@ export function Visualizer({ return; } - const observer = new IntersectionObserver(handleObserving, { - threshold: 0, + const observer = new IntersectionObserver(([entry]) => { + visible.current = entry.isIntersecting; }); observer.observe(canvas.current); return () => { - if (canvas.current) { - observer.unobserve(canvas.current); - } + observer.disconnect(); }; }, [canvas]); - function handleObserving([entry]: IntersectionObserverEntry[]) { - // running.current = !entry.isIntersecting; - } - React.useEffect(() => { return () => { if (interval.current) { @@ -124,20 +119,18 @@ export function Visualizer({ }, []); return ( - <> +
-
- {controls && ( -
- - -
- )} -
- + {controls && ( +
+ + +
+ )} +
); }