import { memo, useEffect, useRef, useState } from "react"; import { AppState } from "react-native"; import { useIsFocused } from "expo-router"; import { useReducedMotion } from "react-native-reanimated"; import Svg, { Path } from "react-native-svg"; import { useTheme } from "../../theme/ThemeProvider"; import { ParticleMotion, particlePaths, type Glyph } from "./particleMotion"; const marks = { ring: "M7.25 22a14.75 14.75 0 1 0 29.5 0a14.75 14.75 0 1 0 -29.5 0", plus: "M10.333 22h23.334M22 10.333v23.334", minus: "M10.333 22h23.334", }; export const ParticleControl = memo(function ParticleControl({ glyph, }: { glyph: Glyph; }) { const { colors } = useTheme(); const focused = useIsFocused(); const reduced = useReducedMotion(); const animator = useRef(null); if (!animator.current) animator.current = new ParticleMotion(glyph); const [frame, setFrame] = useState(() => animator.current!.frame(0, reduced)); useEffect(() => { const motion = animator.current!; motion.setTarget(glyph, reduced); setFrame(motion.frame(0, reduced)); let raf = 0, last = 0, foreground = AppState.currentState === "active"; function tick(now: number) { if (!foreground || !focused) return; if (!last || now - last >= 1000 / 30) { setFrame(motion.frame(last ? Math.min(now - last, 100) : 0, reduced)); last = now; } if (motion.active && !reduced) raf = requestAnimationFrame(tick); } if (focused && foreground && !reduced && motion.active) raf = requestAnimationFrame(tick); const subscription = AppState.addEventListener("change", (state) => { foreground = state === "active"; cancelAnimationFrame(raf); last = 0; if (foreground && focused && !reduced && motion.active) raf = requestAnimationFrame(tick); }); return () => { cancelAnimationFrame(raf); subscription.remove(); }; }, [glyph, focused, reduced]); const shape = frame.glyph && frame.glyph !== "orb" ? marks[frame.glyph] : null; const paths = shape ? [] : particlePaths(frame.dots); return ( {shape ? ( <> ) : ( <> {paths.map((d, i) => ( ))} )} ); });