All files / src/utils usePrefersReducedMotion.ts

100% Statements 14/14
100% Branches 4/4
100% Functions 4/4
100% Lines 12/12

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    20x                 267x 267x 267x 2x     267x 251x 10x 10x 10x   267x   267x    
import { onBeforeUnmount, onMounted, ref, type Ref } from "vue";
 
const QUERY = "(prefers-reduced-motion: reduce)";
 
/** Reactive `prefers-reduced-motion: reduce`.
 *
 *  Starts as false and reads the real preference only once mounted: the
 *  server cannot know it, so reading it during setup would make the first
 *  client render differ from the server HTML (a hydration mismatch).
 *  Stays false where matchMedia doesn't exist (SSR, jsdom, old browsers). */
export function usePrefersReducedMotion(): Ref<boolean> {
  const reduced = ref(false);
  let media: MediaQueryList | null = null;
  const onChange = (event: { matches: boolean }) => {
    reduced.value = event.matches;
  };
 
  onMounted(() => {
    if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
    media = window.matchMedia(QUERY);
    reduced.value = media.matches;
    media.addEventListener("change", onChange);
  });
  onBeforeUnmount(() => media?.removeEventListener("change", onChange));
 
  return reduced;
}