All files / src/lib useReducedMotion.ts

92.85% Statements 13/14
100% Branches 6/6
85.71% Functions 6/7
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 291x       1x     16x       4x 3x 3x 3x     12x 1x               4x    
"use client";
 
import { useSyncExternalStore } from "react";
 
const QUERY = "(prefers-reduced-motion: reduce)";
 
function supported(): boolean {
  return typeof window !== "undefined" && typeof window.matchMedia === "function";
}
 
function subscribe(onChange: () => void): () => void {
  if (!supported()) return () => {};
  const mql = window.matchMedia(QUERY);
  mql.addEventListener("change", onChange);
  return () => mql.removeEventListener("change", onChange);
}
 
const getSnapshot = (): boolean => (supported() ? window.matchMedia(QUERY).matches : false);
const getServerSnapshot = (): boolean => false;
 
// Reports whether the user has asked for reduced motion. The media query is an external
// store, so it is read through useSyncExternalStore: SSR (and the hydration render) get
// false, the real value lands right after mount, and a change to the OS setting
// re-renders through the subscription. Callers that gate animation on this MUST still
// fire any expiry callback (reduced motion suppresses the animation, not the round ending).
export function useReducedMotion(): boolean {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}