import { prefersReducedMotion } from "svelte/motion"; const MAX_STEP = 0.05; /** * Seconds of animation time, advancing each frame while the target is at least `threshold` * in view, `when()` holds and motion isn't reduced. Create it in a component's script. */ export class Loop { time = $state(0); #visible = $state(false); constructor( target: () => Element | undefined, { start = 0, threshold = 0.4, when = (): boolean => true } = {} ) { this.time = start; $effect(() => { const el = target(); if (!el) return; const io = new IntersectionObserver(([e]) => (this.#visible = e!.isIntersecting), { threshold }); io.observe(el); return () => io.disconnect(); }); $effect(() => { if (!this.#visible || !when() || prefersReducedMotion.current) return; let last = performance.now(); const tick = (now: number) => { this.time += Math.min(MAX_STEP, (now - last) / 1000); last = now; frame = requestAnimationFrame(tick); }; let frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }); } }