# All files / src/interaction useElementInteraction.ts

91.14% Statements 422/463
87.35% Branches 76/87
100% Functions 6/6
91.14% Lines 422/463

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
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    4641x
    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
    597x
    597x
    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
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    51x
    51x
    51x
    51x
    51x
    43x
    43x
    43x
    41x
    41x
    41x
    41x
    41x
    41x
    41x
    41x
    41x
    41x
    43x
    43x
    43x
    43x
    43x
    43x
    51x

    51x
    4x
    2x
    2x
    2x
    2x
    2x
    51x
    2x
    2x
    2x
    2x
    2x
    2x
    51x
    2x
    2x
    2x
    2x
    2x
    2x
    51x
    51x

    51x
    51x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    354x
    354x
    354x
    2x
    2x
    354x
    2x
    2x
    354x
    354x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    2254x
    127x
    127x

    127x
    2254x
    2254x
    2254x
    2254x
    183x
    2x
    2x
    181x
    181x
    181x
    181x
    166x
    166x
    183x
    183x
    41x
    183x
    142x
    142x
    142x
    39x
    39x
    39x
    39x
    39x
    39x
    2254x
    2254x
    2254x
    2254x
    146x
    146x
    146x
    146x
    2x
    146x
    146x
    146x
    146x
    2x
    146x
    144x
    144x
    2x
    2x
    2x
    3x

    2x
    2x
    2x
    2x
    3x

    2x
    2x
    2x
    2254x
    2254x
    2254x
    2254x
    133x
    133x
    131x
    131x
    2x
    2x
    2x
    2x
    2254x
    2254x
    2254x
    2254x
    60x
    60x
    60x
    60x
    4x
    4x
    60x
    60x
    60x

    2254x
    2254x
    2254x
    1x
    1x
    1x
    1x

    1x
    1x
    1x

    2254x
    2254x
    78x
    78x
    78x
    78x
    78x
    78x
    75x
    71x
    65x
    9x
    9x
    9x
    9x
    78x
    69x
    69x
    9x
    9x
    9x
    9x
    9x
    9x
    78x
    5x
    2x
    2x
    2x
    5x
    5x
    5x
    9x
    78x
    7x
    7x
    2x
    2x
    2x
    2x
    2254x
    2254x
    2254x
    2254x
    82x
    82x
    82x
    82x
    3x
    3x
    82x
    80x
    80x
    2x
    2x
    2x
    2x
    2254x
    2254x
    2254x
    2254x
    7x
    7x
    7x
    7x

    2254x
    2254x
    2254x
    2254x
    4x
    4x
    4x
    4x

    2254x
    2254x
    2254x
    2254x
    4x
    4x
    4x
    4x

    2254x
    2254x
    2254x
    2254x
    2254x
     "use client";
    import type { FocusEvent, KeyboardEvent, MouseEvent, TouchEvent } from "react";
    import { useCallback, useReducer, useRef } from "react";
    import { useElementInteractionContext } from "./ElementInteractionProvider.js";
    import { useUserInteractionMode } from "./UserInteractionModeProvider.js";
    import type {
      ElementInteractionHandlers,
      ElementInteractionState,
      ProvidedRippleContainerProps,
      RippleState,
      RippleStyle,
    } from "./types.js";
    import { getRippleStyle, releaseRipple, updateRipplesState } from "./utils.js";

    /** @remarks \@since 6.0.0 */
    export const PRESSED_CLASS_NAME = "rmd-pressed";

    /** @remarks \@since 6.0.0 */
    export interface ElementInteractionOptions<E extends HTMLElement>
      extends Partial<ElementInteractionHandlers<E>> {
      /**
       * Boolean if the element is currently disabled which will prevent any of the
       * element interaction states from happening.
       *
       * @defaultValue `false`
       */
      disabled?: boolean;
    }

    /** @remarks \@since 6.0.0 */
    export interface ElementInteractionHookReturnValue<E extends HTMLElement> {
      /**
       * The event handlers required for element interaction.
       */
      handlers: Readonly<ElementInteractionHandlers<E>>;

      /**
       * Boolean if the element is currently pressed. This will always be `false` if
       * the {@link ElementInteractionMode} is set to `"none"`
       */
      pressed: boolean;

      /**
       * This will be set to {@link PRESSED_CLASS_NAME} only when {@link pressed} is
       * `true` and the {@link ElementInteractionMode} is set to `"press"`. It will
       * be `undefined` otherwise.
       */
      pressedClassName: string | undefined;

      /**
       * Props to pass to the {@link RippleContainer} when the
       * {@link ElementInteractionMode} is set to `"ripple"`
       *
       * Note: this will be `undefined` if the {@link ElementInteractionMode} is set
       * to `"none"` or `"press"`
       */
      rippleContainerProps?: Readonly<ProvidedRippleContainerProps>;
    }

    type ElementInteractionAction =
      | { type: "press"; style?: RippleStyle; programmatic?: boolean }
      | { type: "release" | "cancel" }
      | { type: "entered" | "exited"; ripple: RippleState };

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

    /**
     * This hook is used to apply the required element interaction based on the
     * {@link ElementInteractionMode} and should generally be used internally only.
     *
     * @example
     * Providing Element Interaction
     * ```tsx
     * import { useElementInteraction, RippleContainer } from "@react-md/core";
     * import { cnb } from "cnbuilder";
     * import type { ReactElement } from "react";
     *
     * import styles from "./CustomComponent.module.scss";
     *
     * interface Props extends HTMLAttributes<HTMLDivElement> {
     *   disabled?: boolean;
     * }
     *
     * function CustomComponent(props: Props): ReactElement {
     *   const {
     *     disabled = false,
     *     className,
     *     onBlur,
     *     onClick,
     *     onKeyDown,
     *     onKeyUp,
     *     onMouseDown,
     *     onMouseUp,
     *     onMouseLeave,
     *     onTouchStart,
     *     onTouchMove,
     *     onTouchEnd,
     *     ...remaining,
     *   } = props;
     *
     *   const { handlers, pressed, rippleContainerProps } =
     *     useElementInteraction({
     *       disabled,
     *       // pass remaining props so that if any event handlers were provided to
     *       // the component, they will be merged with the element interaction
     *       // handlers
     *       onBlur,
     *       onClick,
     *       onKeyDown,
     *       onKeyUp,
     *       onMouseDown,
     *       onMouseUp,
     *       onMouseLeave,
     *       onTouchStart,
     *       onTouchMove,
     *       onTouchEnd,
     *     })
     *
     *   return (
     *     <div
     *       {...remaining}
     *       {...handlers}
     *       aria-disabled={disabled}
     *       role="button"
     *       className={cnb(styles.button, pressed && styles.pressed)}
     *       tabIndex={disabled ? undefined : 0}
     *     >
     *       {children}
     *       {rippleContainerProps && <RippleContainer {...rippleContainerProps} />}
     *     </div>
     *   );
     * }
     * ```
     *
     * @param options - An object of {@link ElementInteractionOptions} that is used
     * to merge event handlers or disable the interactions.
     * @returns the {@link ElementInteractionHookReturnValue}
     * @remarks \@since 6.0.0 Touch interactions were removed since it never looked
     * good if the user touched a clickable element right before scrolling. The
     * ripple effect will only be fired on click now for touch devices.
     */
    export function useElementInteraction<E extends HTMLElement>(
      options: ElementInteractionOptions<E> = {}
    ): ElementInteractionHookReturnValue<E> {
      const {
        onBlur = noop,
        onClick = noop,
        onMouseDown = noop,
        onMouseUp = noop,
        onMouseLeave = noop,
        onKeyUp = noop,
        onKeyDown = noop,
        onTouchStart = noop,
        onTouchEnd = noop,
        onTouchMove = noop,
        onDragStart = noop,
        disabled = false,
      } = options;

      const holding = useRef(false);
      const disableClick = useRef(false);
      const userMode = useUserInteractionMode();
      const { mode } = useElementInteractionContext();
      const isInteractionDisabled = disabled || mode === "none";
      const [state, dispatch] = useReducer(
        function reducer(
          state: ElementInteractionState,
          action: ElementInteractionAction
        ): ElementInteractionState {
          switch (action.type) {
            case "press": {
              const { style } = action;
              let { ripples } = state;
              if (style) {
                ripples = [
                  ...ripples,
                  {
                    style,
                    entered: false,
                    exiting: false,
                    startTime: Date.now(),
                  },
                ];
              }

              return {
                pressed: true,
                ripples,
              };
            }
            case "cancel":
              // Note: unlike previous react-md versions, this will immediately
              // remove ALL ripple effects instead of trying to fade out. this seems
              // much nicer for touch devices when they are trying to scroll
              return {
                pressed: false,
                ripples: [],
              };
            case "release": {
              if (mode === "press") {
                return { ...state, pressed: false };
              }

              return releaseRipple(state);
            }
            case "entered":
              return updateRipplesState({
                type: "entered",
                state,
                ripple: action.ripple,
                holding: holding.current,
              });
            case "exited":
              return updateRipplesState({
                type: "exited",
                state,
                ripple: action.ripple,
                holding: holding.current,
              });

            default:
              return state;
          }
        },
        { pressed: false, ripples: [] }
      );
      const { pressed, ripples } = state;

      let rippleContainerProps: ProvidedRippleContainerProps | undefined;
      if (mode == "ripple") {
        rippleContainerProps = {
          ripples,
          onEntered(ripple) {
            dispatch({ type: "entered", ripple });
          },
          onExited(ripple) {
            dispatch({ type: "exited", ripple });
          },
        };
      }

      return {
        pressed,
        pressedClassName:
          pressed && mode === "press" ? PRESSED_CLASS_NAME : undefined,
        rippleContainerProps,
        handlers: {
          onBlur: useCallback(
            (event: FocusEvent<E>) => {
              onBlur(event);
              if (holding.current) {
                holding.current = false;
                dispatch({ type: "release" });
              }
            },
            [onBlur]
          ),
          onClick: useCallback(
            (event: MouseEvent<E>) => {
              if (disabled) {
                return;
              }

              onClick(event);
              if (
                event.isPropagationStopped() ||
                userMode === "touch" ||
                mode !== "ripple" ||
                disableClick.current ||
                holding.current ||
                document.activeElement === event.currentTarget
              ) {
                disableClick.current = false;
                return;
              }

              dispatch({
                type: "press",
                style: getRippleStyle(event, true),
              });
            },
            [disabled, mode, onClick, userMode]
          ),
          onMouseDown: useCallback(
            (event: MouseEvent<E>) => {
              onMouseDown(event);
              if (
                event.isPropagationStopped() ||
                isInteractionDisabled ||
                userMode !== "mouse" ||
                event.shiftKey ||
                event.ctrlKey ||
                event.metaKey ||
                event.altKey ||
                event.button !== 0
              ) {
                return;
              }

              // prevent text selection on double click
              // https://stackoverflow.com/a/43321596
              if (event.detail > 1) {
                event.preventDefault();
              }

              holding.current = true;
              disableClick.current = true;
              let style: RippleStyle | undefined;
              if (mode === "ripple") {
                style = getRippleStyle(event, false);
              }

              dispatch({ type: "press", style });
            },
            [onMouseDown, isInteractionDisabled, userMode, mode]
          ),
          onMouseUp: useCallback(
            (event: MouseEvent<E>) => {
              onMouseUp(event);
              if (event.isPropagationStopped() || isInteractionDisabled) {
                return;
              }

              holding.current = false;
              dispatch({ type: "release" });
            },
            [isInteractionDisabled, onMouseUp]
          ),
          onMouseLeave: useCallback(
            (event: MouseEvent<E>) => {
              onMouseLeave(event);
              if (
                event.isPropagationStopped() ||
                isInteractionDisabled ||
                userMode !== "mouse" ||
                !holding.current
              ) {
                return;
              }

              holding.current = false;
              dispatch({ type: "cancel" });
            },
            [isInteractionDisabled, onMouseLeave, userMode]
          ),
          onDragStart(event) {
            onDragStart(event);
            if (
              event.isPropagationStopped() ||
              !holding.current ||
              userMode !== "mouse"
            ) {
              return;
            }

            holding.current = false;
            dispatch({ type: "cancel" });
          },
          onKeyDown: useCallback(
            (event: KeyboardEvent<E>) => {
              onKeyDown(event);
              const { key } = event;
              const { tagName } = event.currentTarget;

              if (
                event.isPropagationStopped() ||
                userMode !== "keyboard" ||
                disabled ||
                (key !== " " && key !== "Enter") ||
                // links do not support clicking on space
                (key === " " && tagName === "A") ||
                // inputs submit a form instead of clicking on enter
                (key === "Enter" && tagName === "INPUT")
              ) {
                return;
              }

              // stop propagation since we're starting to do custom event behavior
              // to click the element for everything except elements that the
              // browser clicks natively
              event.stopPropagation();

              if (tagName !== "BUTTON" && tagName !== "A") {
                if (key === " ") {
                  // prevent the pager from scrolling
                  event.preventDefault();
                }

                event.currentTarget.click();
              }

              if (holding.current || isInteractionDisabled) {
                return;
              }

              holding.current = true;
              dispatch({ type: "press", style: getRippleStyle(event, false) });
            },
            [disabled, isInteractionDisabled, onKeyDown, userMode]
          ),
          onKeyUp: useCallback(
            (event: KeyboardEvent<E>) => {
              onKeyUp(event);
              if (
                event.isPropagationStopped() ||
                isInteractionDisabled ||
                userMode !== "keyboard" ||
                !holding.current
              ) {
                return;
              }

              holding.current = false;
              dispatch({ type: "release" });
            },
            [isInteractionDisabled, onKeyUp, userMode]
          ),
          onTouchStart: useCallback(
            (event: TouchEvent<E>) => {
              onTouchStart(event);
              if (event.isPropagationStopped() || isInteractionDisabled) {
                return;
              }

              holding.current = true;
              let style: RippleStyle | undefined;
              if (mode === "ripple") {
                style = getRippleStyle(event, false);
              }

              dispatch({ type: "press", style });
            },
            [mode, isInteractionDisabled, onTouchStart]
          ),
          onTouchEnd: useCallback(
            (event: TouchEvent<E>) => {
              onTouchEnd(event);
              if (event.isPropagationStopped() || isInteractionDisabled) {
                return;
              }

              holding.current = false;
              dispatch({ type: "release" });
            },
            [isInteractionDisabled, onTouchEnd]
          ),
          onTouchMove: useCallback(
            (event: TouchEvent<E>) => {
              onTouchMove(event);
              if (event.isPropagationStopped() || isInteractionDisabled) {
                return;
              }

              holding.current = false;
              dispatch({ type: "cancel" });
            },
            [isInteractionDisabled, onTouchMove]
          ),
        },
      };
    }