File size: 993 Bytes
61db3dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useEffect, useState, type RefObject } from "react"

/** Whether the visitor asked for less motion (videos then hold their first frame). */
export function useReducedMotion() {
  const q = "(prefers-reduced-motion: reduce)"
  const [on, setOn] = useState(() => matchMedia(q).matches)
  useEffect(() => {
    const mq = matchMedia(q)
    const f = () => setOn(mq.matches)
    mq.addEventListener("change", f)
    return () => mq.removeEventListener("change", f)
  }, [])
  return on
}

/** Plays a muted loop only while it is on screen and motion is welcome. */
export function useLoop(ref: RefObject<HTMLVideoElement | null>) {
  const still = useReducedMotion()
  useEffect(() => {
    const v = ref.current
    if (!v) return
    if (still) {
      v.pause()
      return
    }
    const io = new IntersectionObserver(([e]) => (e.isIntersecting ? v.play().catch(() => {}) : v.pause()), { rootMargin: "120px" })
    io.observe(v)
    return () => io.disconnect()
  }, [ref, still])
}