summaryrefslogtreecommitdiff
path: root/shared/components/src/stores/prefers-reduced-motion.ts
blob: 03d9393e0985a34cc05f620c96c25831c6b543d4 (plain)
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
import { readable } from 'svelte/store';

const DEFAULT_SETTING = false;

export const prefersReducedMotion = readable(DEFAULT_SETTING, (set) => {
    if (typeof window === 'undefined' || typeof matchMedia === 'undefined') {
        set(DEFAULT_SETTING);
        return;
    }

    const motionQuery = matchMedia('(prefers-reduced-motion)');

    /* istanbul ignore next */
    const motionQueryListener = (): void => {
        set(motionQuery.matches);
    };

    // `addListener` is deprecated but should still be used for compatibility with more browsers.
    motionQuery.addListener(motionQueryListener);

    set(motionQuery.matches);

    return function (): void {
        // `removeListener` is deprecated but should still be used for compatibility with more browsers.
        motionQuery.removeListener(motionQueryListener);
    };
});