# All files / interaction UserInteractionModeProvider.tsx

91.91% Statements 182/198
94.73% Branches 18/19
71.42% Functions 5/7
91.91% Lines 182/198

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
    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
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    1991x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    2157x
    2157x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    67x
    67x
    67x
    67x
    67x

    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    67x
    51x
    51x
    51x
    51x
    1x
    1x
    1x
    1x
    51x
    51x

    51x

    51x
    51x
    51x
    51x
    51x
    38x
    50x
    12x
    13x
    1x
    1x
    1x
    51x
    51x
    51x
    51x
    51x
    38x
    50x
    12x
    13x
    1x
    1x
    1x
    51x
    67x
    67x
    67x
    67x
    51x
    51x
    51x
    67x
    67x
    67x
    67x
     "use client";
    import {
      createContext,
      useContext,
      useEffect,
      useMemo,
      useRef,
      useState,
      type ReactElement,
      type ReactNode,
    } from "react";

    /**
     * This is the current mode for how your user is interacting with your app. This
     * will be used to determine which type of state styles should be applied at the
     * time of interacting with an element on your page.
     *
     * @defaultValue `"mouse"`
     */
    export type UserInteractionMode = "keyboard" | "mouse" | "touch";

    /** @internal */
    interface UserInteractionModeContext {
      __root: boolean;
      mode: UserInteractionMode;
    }

    const context = createContext<UserInteractionModeContext>({
      __root: false,
      mode: "mouse",
    });
    context.displayName = "UserInteractionMode";
    const { Provider } = context;

    /**
     * @returns the current user interaction mode
     */
    export function useUserInteractionMode(): UserInteractionMode {
      return useContext(context).mode;
    }

    /** @internal */
    const TOUCH_TIMEOUT = 1200;

    export interface UserInteractionModeProviderProps {
      children: ReactNode;
    }

    /**
     * **Client Component**
     *
     * This component is used to determine how a user is interacting with your app
     * to update component functionality and applying the following class names to
     * the `document.body`:
     *
     * - `"mouse-mode"`
     * - `"keyboard-mode"`
     * - `"touch-mode"`
     *
     * Within `react-md`, these classes are used for the following behavior:
     * - only display `:focus` outlines while in `"keyboard-mode"`
     * - do not display `:hover` effects while in `"touch-mode"`
     *
     * @example
     * Mount at the root of your app
     * ```tsx
     * import { createRoot } from "react-dom/client";
     * import { UserInteractionModeProvider } from "@react-md/core";
     * import App from "./App":
     *
     * const container = document.getElementById("root");
     * const root = createRoot(container);
     *
     * root.render(
     *   <UserInteractionModeProvider>
     *     <App />
     *   </UserInteractionModeProvider>
     * );
     * ```
     *
     * @throws "The `UserInteractionModeProvider` cannot be mounted multiple times."
     * if this component is mounted multiple times in your app.
     */
    export function UserInteractionModeProvider(
      props: UserInteractionModeProviderProps
    ): ReactElement {
      const { children } = props;
      const { __root } = useContext(context);
      if (__root) {
        throw new Error(
          "The `UserInteractionModeProvider` cannot be mounted multiple times."
        );
      }

      const [mode, setMode] = useState<UserInteractionMode>("mouse");
      const lastTouchTime = useRef(0);
      const isTouchContextMenu = useRef(false);

      /**
       * This effect helps determine the current interaction mode by attaching the
       * required event listeners to the window. The `mode` will always be defaulted
       * to `mouse` at first since it has the least possibilities of causing errors
       * with styles since the mouse-only styles are normally just `:hover` effects.
       *
       * ## Switching between modes:
       *
       * ### While in `mouse` mode:
       *
       * - any `keydown` event will switch to `keyboard` mode
       *   - this does have the side effect of meta keys also causing the switch over,
       *     but it feels fine since it helps show the current focus in the document
       *     as well
       * - any `touchstart` event will switch to `touch` mode
       *
       * ### While in `keyboard` mode:
       *
       * - any `mousedown` event will switch to `mouse` mode
       *   - it is perfectly okay to move the mouse while in keyboard mode, but still
       *     want to keep the keyboard styles until the user actually starts clicking
       * - any `touchstart` event will switch to `touch` mode
       *
       * ### While in `touch` mode:
       *
       * - any `mousemove` event will switch to `mouse` mode, but **only** if there
       *   hasn't been a `contextmenu` event within the last `1.2s`
       *   - you can really only switch back to `mouse` mode if you are using the
       *     devtools to emulate devices OR using a touch-desktop. I don't know how
       *     common this really is though.
       *   - touching the screen will always fire a `mousemove` event (which is why
       *     the `:hover` styles are normally with `rmd-utils-mouse-only`) and even
       *     after the `contextmenu` event. Normally want to go back to `mouse` mode
       *     when the mouse re-enters the `window`
       *
       * Note: It's currently impossible to switch from `touch` to `keyboard`
       * immediately. You'd first need to switch to `mouse` and then to `keyboard`. I
       * don't really know of any use-cases other than the weird touch-desktop stuff
       * and I have no experience using them.
       */
      useEffect(() => {
        const enableMouseMode = (): void => setMode("mouse");
        const enableKeyboardMode = (): void => setMode("keyboard");

        const handleTouchStart = (): void => {
          lastTouchTime.current = Date.now();
          isTouchContextMenu.current = false;
          setMode("touch");
        };

        const handleMouseMove = (): void => {
          if (
            isTouchContextMenu.current ||
            Date.now() - lastTouchTime.current < TOUCH_TIMEOUT
          ) {
            isTouchContextMenu.current = false;
            return;
          }

          enableMouseMode();
        };
        const handleContextMenu = (): void => {
          isTouchContextMenu.current = true;
        };

        const className = `${mode}-mode`;
        document.body.classList.add(className);
        window.addEventListener("touchstart", handleTouchStart, true);
        if (mode === "mouse") {
          window.addEventListener("keydown", enableKeyboardMode, true);
        } else if (mode === "keyboard") {
          window.addEventListener("mousedown", enableMouseMode, true);
        } else {
          window.addEventListener("mousemove", handleMouseMove, true);
          window.addEventListener("contextmenu", handleContextMenu, true);
        }

        return () => {
          document.body.classList.remove(className);
          window.removeEventListener("touchstart", handleTouchStart, true);
          if (mode === "mouse") {
            window.removeEventListener("keydown", enableKeyboardMode, true);
          } else if (mode === "keyboard") {
            window.removeEventListener("mousedown", enableMouseMode, true);
          } else {
            window.removeEventListener("mousemove", handleMouseMove, true);
            window.removeEventListener("contextmenu", handleContextMenu, true);
          }
        };
      }, [mode]);

      const value = useMemo<UserInteractionModeContext>(
        () => ({
          mode,
          __root: true,
        }),
        [mode]
      );
      return <Provider value={value}>{children}</Provider>;
    }