# All files / src/hoverMode useHoverModeProvider.ts

99.03% Statements 308/311
91.66% Branches 11/12
100% Functions 3/3
99.03% Lines 308/311

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
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    3121x
    1x
    1x
    1x
    1x
    70x
    70x
    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
    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
    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
    1x
    1x
    1x
    1x
    1x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    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
    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
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    39x
    214x
    214x
    214x
    20x
    20x
    20x
    20x
    20x
    16x
    16x
    20x
    214x
    214x
    214x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    214x
    214x
    4x

    4x
    4x
    4x

    4x
    214x
    214x
    214x
    41x
    41x
    41x
    41x
    214x
    214x
    214x
    214x
    62x
    62x
    62x
    62x
    62x
    62x
    62x
    62x
    62x
    62x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
    214x
     "use client";
    import { useCallback, useEffect, useMemo, useRef, useState } from "react";
    import type { NonNullMutableRef, NonNullRef } from "../types.js";

    const noop = (): void => {
      // do nothing
    };

    /** @remarks \@since 6.0.0 */
    export interface SimpleHoverModeContext {
      /**
       * @example
       * Main Usage
       * ```ts
       * onMouseEnter(event) {
       *   const hoverTimeout = hoverTimeoutRef.current;
       *   if (typeof hoverTimeout !== "number" || mode === "touch") {
       *     return;
       *   }
       *
       *   const { id } = event.currentTarget;
       *   clearDisableTimer();
       *   window.clearTimeout(visibilityTimeout.current);
       *   visibilityTimeout.current = window.setTimeout(() => {
       *     enableHoverMode(id);
       *     setVisible(true);
       *   }, hoverTimeout);
       * }
       * ```
       */
      hoverTimeoutRef: NonNullRef<number | undefined>;

      /**
       * @example
       * Main Usage
       * ```ts
       * onMouseLeave() {
       *   if (mode === "touch") {
       *     return
       *   }
       *
       *   startDisableTimer();
       *   window.clearTimeout(visibilityTimeout.current);
       *   visibilityTimeout.current = window.setTimeout(() => {
       *     setVisible(false)
       *   }, leaveTimeoutRef.current);
       * }
       * ```
       */
      leaveTimeoutRef: NonNullRef<number>;

      /**
       * When this is called, the {@link hoverTimeoutRef} will be set to `0` and the
       * {@link HoverModeContext.activeId} will be set to this `activeId` value.
       *
       * @see {@link hoverTimeoutRef} for an example.
       */
      enableHoverMode(activeId: string): void;

      /**
       * Disables all hover mode behavior by clearing all timeouts and resetting
       * internal state.
       */
      disableHoverMode(): void;

      /**
       * @see {@link leaveTimeoutRef} for an example.
       */
      startDisableTimer(): void;

      /**
       * @see {@link hoverTimeoutRef} for an example.
       */
      clearDisableTimer(): void;
    }

    /**
     * @remarks
     * \@since 2.8.0
     * \@since 6.0.0 Uses refs to increase performance by preventing unneeded
     * re-renders of the entire hover mode provider's component tree. The API also
     * changed to support custom hover mode providers.
     */
    export interface HoverModeContext extends SimpleHoverModeContext {
      /**
       * This will only be updated if {@link HoverModeConfiguration.forceRerender} is `true`
       */
      activeId: string;

      /**
       * This ref contains the current DOM `id` for the element that is being
       * hovered within the `HoverModeProvider`. This will be an empty string
       * when the hover mode is not active.
       */
      activeIdRef: NonNullMutableRef<string>;

      /**
       * This ref can be used to disable transitions for a group of components using
       * the same hover mode provider. The general flow would be:
       *
       * - set `disableTransition: animatedOnceRef.current` on hover mode components
       * - set `animatedOnceRef.current = true` when the `onEntered` transition callback fires
       * - set `animatedOnceRef.current = false` when the hover mode behavior is
       *   disabled. This would normally be after a timeout for the `onExited`
       *   callback
       */
      animatedOnceRef: NonNullMutableRef<boolean>;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export interface CreateHoverModeContextOptions {
      /**
       * TODO: I think this has something to do with how I implemented the MenuBar.
       *
       * @defaultValue `""`
       */
      defaultActiveId?: string;

      /**
       * When this is `undefined`, the hover mode behavior will be disabled.
       * Otherwise, this will be the amount of time to wait on a `mouseenter` event
       * before setting the visibility to `true`.
       *
       * @defaultValue `undefined`
       */
      hoverTimeout?: number;

      /**
       * The amount of time to wait after a `mouseleave` event before setting the
       * visibility to `false`.
       *
       * @defaultValue `0`
       * @remarks \@since 6.0.0 This was renamed from `exitVisibilityDelay` and the
       * default value changed from `300` to `0`.
       */
      leaveTimeout?: number;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export function createHoverModeContext(
      options: CreateHoverModeContextOptions = {}
    ): Readonly<HoverModeContext> {
      const { defaultActiveId = "", hoverTimeout, leaveTimeout = 0 } = options;

      return {
        activeId: defaultActiveId,
        activeIdRef: { current: defaultActiveId },
        hoverTimeoutRef: { current: hoverTimeout },
        leaveTimeoutRef: { current: leaveTimeout },
        animatedOnceRef: { current: false },
        enableHoverMode: noop,
        disableHoverMode: noop,
        startDisableTimer: noop,
        clearDisableTimer: noop,
      };
    }

    /** @remarks \@since 6.0.0 */
    export interface HoverModeConfiguration extends CreateHoverModeContextOptions {
      /**
       * The amount of time to wait before disabling the hover mode behavior if none
       * of the components are being hovered.
       *
       * If this is `undefined`, {@link HoverModeContext.startDisableTimer} will do
       * nothing. You must manually call {@link HoverModeContext.disableHoverMode}
       * to disable the hover mode instead.
       */
      disableTimeout?: number;

      /**
       * @defaultValue `false`
       */
      forceRerender?: boolean;
    }

    /**
     * @example
     * Creating a Hover Mode Group
     * ```tsx
     * import type {
     *   HoverModeConfiguration,
     *   HoverModeContext,
     * } from "@react-md/core";
     * import {
     *   createHoverModeContext,
     *   useHoverModeProvider,
     * } from "@react-md/core";
     * import type { ReactElement } from "react";
     * import { createContext, useContext } from "react";
     *
     * // extend as needed
     * type CustomHoverMode = HoverModeContext;
     *
     * // you can also add defaults if there is no parent provider.
     * const context = createContext<CustomHoverMode>(createHoverModeContext());
     * const { Provider } = context;
     *
     * interface Props extends HoverModeConfiguration {
     *   children: ReactNode;
     * }
     *
     * export function CustomHoverModeProvider({
     *   children,
     *   // change to whatever defaults you want
     *   hoverTimeout = 3000,
     *   leaveTimeout = 3000,
     *   defaultActiveId = "",
     *   disableTimeout = 5000,
     * }: Props): ReactElement {
     *   const context = useHoverModeProvider({
     *     hoverTimeout,
     *     leaveTimeout,
     *     defaultActiveId,
     *     disableTimeout,
     *   });
     *
     *   return <Provider value={context}>{children}</Provider>;
     * }
     * ```
     *
     * @see {@link CreateHoverModeContextOptions}
     * @see {@link useHoverMode}
     * @remarks \@since 6.0.0 The `HoverModeProvider` component was replaced by this
     * hook implementation. After developing the `MenuBar`, I realized the hover
     * mode should normally be grouped by related components or types instead of a
     * top-level catch all.
     */
    export function useHoverModeProvider(
      options: HoverModeConfiguration
    ): Readonly<HoverModeContext> {
      const {
        hoverTimeout,
        leaveTimeout = 0,
        forceRerender = false,
        defaultActiveId = "",
        disableTimeout,
      } = options;

      const [activeId, setActiveId] = useState(defaultActiveId);
      const activeIdRef = useRef(defaultActiveId);
      const hoverTimeoutRef = useRef(hoverTimeout);
      const leaveTimeoutRef = useRef(leaveTimeout);
      const animatedOnceRef = useRef(!!defaultActiveId);
      const disableHoverModeTimeout = useRef<number | undefined>();
      const clearDisableTimer = useCallback(() => {
        window.clearTimeout(disableHoverModeTimeout.current);
      }, []);
      const enableHoverMode = useCallback(
        (activeId: string) => {
          clearDisableTimer();
          activeIdRef.current = activeId;
          hoverTimeoutRef.current = 0;

          if (forceRerender) {
            setActiveId(activeId);
          }
        },
        [clearDisableTimer, forceRerender]
      );
      const disableHoverMode = useCallback(() => {
        clearDisableTimer();
        activeIdRef.current = "";
        hoverTimeoutRef.current = hoverTimeout;
        animatedOnceRef.current = false;
        if (forceRerender) {
          setActiveId("");
        }
      }, [clearDisableTimer, forceRerender, hoverTimeout]);
      const startDisableTimer = useCallback(() => {
        if (typeof disableTimeout !== "number") {
          return;
        }

        clearDisableTimer();
        disableHoverModeTimeout.current = window.setTimeout(() => {
          disableHoverMode();
        }, disableTimeout);
      }, [clearDisableTimer, disableHoverMode, disableTimeout]);

      useEffect(() => {
        hoverTimeoutRef.current = hoverTimeout;
        return () => {
          window.clearTimeout(disableHoverModeTimeout.current);
        };
      }, [hoverTimeout]);

      return useMemo<HoverModeContext>(
        () => ({
          activeId,
          activeIdRef,
          hoverTimeoutRef,
          leaveTimeoutRef,
          animatedOnceRef,
          enableHoverMode,
          disableHoverMode,
          startDisableTimer,
          clearDisableTimer,
        }),
        [
          activeId,
          enableHoverMode,
          disableHoverMode,
          startDisableTimer,
          clearDisableTimer,
        ]
      );
    }