aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/providers/motion-provider/motion-provider.tsx
blob: dfedcaa8c3e30007b296b18ec104d49ad5606966 (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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
  type Dispatch,
  type FC,
  type ReactNode,
  type SetStateAction,
  createContext,
  useMemo,
  useCallback,
  useEffect,
} from 'react';
import { getDataAttributeFrom } from '../../helpers';
import { useLocalStorage } from '../../hooks';

type MotionContextProps = {
  isReduced: boolean;
  setIsReduced: Dispatch<SetStateAction<boolean>>;
  toggleReducedMotion: () => void;
};

export const MotionContext = createContext<MotionContextProps>({
  isReduced: false,
  setIsReduced: (value) => value,
  toggleReducedMotion: () => null,
});

const validator = (value: unknown): value is boolean =>
  typeof value === 'boolean';

export type MotionProviderProps = {
  /**
   * The attribute name to append to document root.
   */
  attribute: string;
  /**
   * The provider children.
   */
  children?: ReactNode;
  /**
   * Is reduced motion currently active?
   *
   * @default false
   */
  hasReducedMotion?: boolean;
  /**
   * The key to use in local storage.
   */
  storageKey: string;
};

export const MotionProvider: FC<MotionProviderProps> = ({
  attribute,
  children,
  hasReducedMotion = false,
  storageKey,
}) => {
  const [isReduced, setIsReduced] = useLocalStorage(
    storageKey,
    hasReducedMotion,
    validator
  );
  const dataAttribute = getDataAttributeFrom(attribute);

  useEffect(() => {
    if (typeof window !== 'undefined')
      document.documentElement.setAttribute(dataAttribute, `${isReduced}`);

    return () => {
      document.documentElement.removeAttribute(dataAttribute);
    };
  }, [dataAttribute, isReduced]);

  const toggleReducedMotion = useCallback(() => {
    setIsReduced((prevState) => !prevState);
  }, [setIsReduced]);

  const value: MotionContextProps = useMemo(() => {
    return { isReduced, setIsReduced, toggleReducedMotion };
  }, [isReduced, setIsReduced, toggleReducedMotion]);

  return (
    <MotionContext.Provider value={value}>{children}</MotionContext.Provider>
  );
};