import { useEffect, useRef, useState } from "react"; import { useTilt } from "./useTilt"; import { createBubbleWorld, screenGravity, DRAW_BUBBLE_RADIUS, } from "../shared/bubble-physics.js"; export function useBubblePhysics(count: number) { const canvas = useRef(null); const world = useRef | null>(null); const kick = useRef<() => void>(() => {}); const redraw = useRef<() => void>(() => {}); const { enabled } = useTilt(); const [reduced, setReduced] = useState( () => matchMedia("(prefers-reduced-motion: reduce)").matches, ); const countRef = useRef(count); countRef.current = count; useEffect(() => { const media = matchMedia("(prefers-reduced-motion: reduce)"); const change = () => setReduced(media.matches); media.addEventListener("change", change); return () => media.removeEventListener("change", change); }, []); useEffect(() => { const element = canvas.current!; const context = element.getContext("2d"); if (!context) return; const simulation = createBubbleWorld(countRef.current); world.current = simulation; let frame = 0; let previous = 0; let accumulator = 0; let disposed = false; let topColor = ""; let bottomColor = ""; const palette = () => { const style = getComputedStyle(element); topColor = style.getPropertyValue("--orb-light").trim(); bottomColor = style.getPropertyValue("--orb-dark").trim(); draw(); }; function draw() { if (!context || disposed) return; context.setTransform( element.width / 320, 0, 0, element.height / 320, 0, 0, ); context.clearRect(0, 0, 320, 320); const gradient = context.createLinearGradient(0, 20, 0, 300); gradient.addColorStop(0, topColor || "#b1bafa"); gradient.addColorStop(1, bottomColor || "#8391ed"); context.fillStyle = gradient; for (const ball of simulation.balls) { context.globalAlpha = 0.72 + (ball.id % 4) * 0.08; context.beginPath(); context.arc( ball.position.x, ball.position.y, DRAW_BUBBLE_RADIUS, 0, Math.PI * 2, ); context.fill(); } context.globalAlpha = 1; element.dataset.bubbles = String(simulation.balls.length); element.dataset.gravityX = simulation.engine.gravity.x.toFixed(3); element.dataset.gravityY = simulation.engine.gravity.y.toFixed(3); } const resize = () => { const size = element.getBoundingClientRect(); const dpr = Math.min(devicePixelRatio || 1, 2); element.width = Math.round(size.width * dpr); element.height = Math.round(size.height * dpr); draw(); }; const observer = new ResizeObserver(resize); observer.observe(element); const theme = new MutationObserver(palette); theme.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "style"], }); function tick(now: number) { frame = 0; if (document.hidden || disposed) { previous = 0; return; } accumulator += previous ? Math.min(now - previous, 50) : 1000 / 60; previous = now; while (accumulator >= 1000 / 60) { simulation.step(); accumulator -= 1000 / 60; } draw(); if (simulation.awake()) frame = requestAnimationFrame(tick); else previous = 0; } const start = () => { if (!frame && !document.hidden && !reduced && !disposed) frame = requestAnimationFrame(tick); }; kick.current = start; redraw.current = draw; const visibility = () => { if (document.hidden) { cancelAnimationFrame(frame); frame = 0; previous = 0; accumulator = 0; } else start(); }; document.addEventListener("visibilitychange", visibility); palette(); resize(); start(); return () => { disposed = true; cancelAnimationFrame(frame); observer.disconnect(); theme.disconnect(); document.removeEventListener("visibilitychange", visibility); simulation.dispose(); world.current = null; kick.current = () => {}; redraw.current = () => {}; }; }, [reduced]); useEffect(() => { if (reduced) { world.current?.seed(count); redraw.current(); } else { world.current?.setTarget(count); kick.current(); } }, [count, reduced]); useEffect(() => { if (!enabled || reduced) { world.current?.gravity(0, 1); kick.current(); return; } let lastBeta = 0; let lastGamma = 0; const apply = () => { const angle = screen.orientation?.angle ?? (window as Window & { orientation?: number }).orientation ?? 0; const next = screenGravity(lastBeta, lastGamma, angle); if (world.current?.gravity(next.x, next.y)) kick.current(); }; const orientation = (event: DeviceOrientationEvent) => { if ( document.hidden || event.beta === null || event.gamma === null || !Number.isFinite(event.beta) || !Number.isFinite(event.gamma) ) return; lastBeta = event.beta; lastGamma = event.gamma; apply(); }; window.addEventListener("deviceorientation", orientation); screen.orientation?.addEventListener("change", apply); return () => { window.removeEventListener("deviceorientation", orientation); screen.orientation?.removeEventListener("change", apply); }; }, [enabled, reduced]); return { canvas }; }