import { useState, useEffect, useRef } from "react"; import { getStoredAnimationId, getNextAnimation, saveAnimation, } from "@/lib/animations/engine"; import { ANIMATION_LABELS } from "@/lib/animations"; export default function AnimationSwitcher() { const [hovering, setHovering] = useState(false); const [currentLabel, setCurrentLabel] = useState(""); const committedRef = useRef(""); useEffect(() => { committedRef.current = getStoredAnimationId(); setCurrentLabel(ANIMATION_LABELS[committedRef.current]); const handleSwap = () => { const id = getStoredAnimationId(); committedRef.current = id; setCurrentLabel(ANIMATION_LABELS[id]); }; document.addEventListener("astro:after-swap", handleSwap); return () => { document.removeEventListener("astro:after-swap", handleSwap); }; }, []); const handleClick = () => { const nextId = getNextAnimation( committedRef.current as Parameters[0] ); saveAnimation(nextId); committedRef.current = nextId; setCurrentLabel(ANIMATION_LABELS[nextId]); document.dispatchEvent( new CustomEvent("animation-changed", { detail: { id: nextId } }) ); }; return (
setHovering(true)} onMouseLeave={() => setHovering(false)} onClick={handleClick} style={{ cursor: "pointer" }} > {currentLabel}
); }