# All files / src/focus useFocusContainer.ts

100% Statements 266/266
100% Branches 39/39
100% Functions 5/5
100% Lines 266/266

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
    2671x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    77x
    77x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    182x
    115x
    115x
    67x
    67x
    638x
    638x
    638x
    638x
    1276x
    85x
    85x
    85x
    85x
    84x
    61x
    53x
    85x
    52x
    52x
    85x
    638x
    638x
    638x
    53x
    53x
    27x
    27x
    26x
    26x
    26x
    26x
    24x
    24x
    26x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    638x
    46x
    46x
    46x
    37x
    14x
    46x
    33x
    33x
    13x
    13x
    13x
    13x
    36x
    4x
    4x
    4x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    7x
    46x
    3x
    34x
    6x
    2x
    6x
    1x
    1x
    9x
    34x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    46x
    638x
    638x
    638x
     "use client";
    import type { KeyboardEventHandler, Ref, RefObject } from "react";
    import { useEffect, useRef } from "react";
    import { TRANSITION_CONFIG } from "../transition/config.js";
    import type {
      TransitionCallbacks,
      TransitionEnterHandler,
      TransitionExitHandler,
    } from "../transition/types.js";
    import { useEnsuredRef } from "../useEnsuredRef.js";
    import type { FocusElementWithinType } from "./utils.js";
    import { focusElementWithin, getFocusableElements } from "./utils.js";

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

    /**
     * `"mount"` - this will attempt to focus the container element if:
     * - there is no `document.activeElement`
     * - the container element does not contain the `document.activeElement`
     *
     * `"unmount"` - attempts to re-focus the element that was focused before the
     * focus container became active. The previous focus element is captured
     * whenever the `activate` option on the `useFocusContainer` hook is set to
     * `true`. This is normally when an element becomes `visible`.
     *
     * `"keyboard"` - refocuses the first focusable element if pressing `Tab` would
     * move the focus outside of the container element. If `Shift + Tab` was used,
     * the last focusable element will be used instead.
     *
     * @remarks \@since 6.0.0
     */
    export type FocusType = "mount" | "unmount" | "keyboard";

    /** @remarks \@since 6.0.0 */
    export type FocusContainerTransitionCallbacks = Pick<
      TransitionCallbacks,
      "onEntering" | "onEntered" | "onExiting" | "onExited"
    >;

    /** @remarks \@since 6.0.0 */
    export interface FocusContainerTransitionOptions<E extends HTMLElement>
      extends FocusContainerTransitionCallbacks {
      /**
       * An optional ref that will be merged with the
       * {@link FocusContainerImplementation.nodeRef}
       */
      nodeRef?: Ref<E>;
    }

    /** @remarks \@since 6.0.0 */
    export interface FocusContainerEventHandlers<E extends HTMLElement> {
      onKeyDown?: KeyboardEventHandler<E>;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export type IsFocusTypeDisabled = (type: FocusType) => boolean;

    export interface FocusContainerComponentProps {
      /**
       * @defaultValue `() => false`
       */
      isFocusTypeDisabled?: IsFocusTypeDisabled;

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

    /** @remarks \@since 6.0.0 */
    export interface FocusContainerOptions<E extends HTMLElement>
      extends FocusContainerTransitionOptions<E>,
        FocusContainerComponentProps {
      onKeyDown?: KeyboardEventHandler<E>;
      /**
       * This to `true` will capture the current focused element as a focus target
       * once the `onExited` hook is fired. This should usually be set to the
       * `transitionIn` prop for `useTransition`.
       */
      activate: boolean;

      /**
       * Set this to true if elements that can be programmatically focused should be
       * included. These would be elements with a `tabIndex={-1}`.
       *
       * @defaultValue `false`
       */
      programmatic?: boolean;
    }

    /** @remarks \@since 6.0.0 */
    export interface FocusContainerImplementation<E extends HTMLElement> {
      nodeRef: RefObject<E>;
      eventHandlers: Required<FocusContainerEventHandlers<E>>;
      transitionOptions: Required<FocusContainerTransitionOptions<E>>;
    }

    /**
     * This hook is mostly for internal use only for dialog accessibility behavior
     * to prevent the focus from moving outside of the dialog while it is visible.
     * This API was developed to be used with the `useCSSTransition`/`useTransition`
     * hooks as well.
     *
     * @example
     * Main Usage
     * ```tsx
     * import {
     *   Button,
     *   useFocusContainer,
     *   useScaleTransition,
     *   useToggle,
     * } from "@react-md/core";
     * import type { ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const { toggled, enable, disable } = useToggle(false);
     *
     *   const { eventHandlers, transitionOptions } = useFocusContainer({
     *     activate: toggled,
     *   });
     *   const { elementProps, rendered } = useScaleTransition({
     *     transitionIn: toggled,
     *     temporary: true,
     *     ...transitionOptions,
     *   });
     *
     *   return (
     *     <>
     *       <Button onClick={enable}>Toggle</Button>
     *       {rendered && (
     *         <div {...eventHandlers} {...elementProps}>
     *           <Button onClick={disable}>Button 1</Button>
     *           <Button onClick={disable}>Button 2</Button>
     *           <Button onClick={disable}>Button 3</Button>
     *           <Button onClick={disable}>Button 4</Button>
     *         </div>
     *       )}
     *     </>
     *   );
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export function useFocusContainer<E extends HTMLElement>(
      options: FocusContainerOptions<E>
    ): FocusContainerImplementation<E> {
      const {
        nodeRef,
        activate,
        onEntering = noop,
        onEntered = noop,
        onExiting = noop,
        onExited = noop,
        onKeyDown = noop,
        programmatic = false,
        disableTransition = false,
        isFocusTypeDisabled = noop,
      } = options;

      const [ref, refCallback] = useEnsuredRef(nodeRef);
      const prevFocus = useRef<HTMLElement | null>(null);

      useEffect(() => {
        if (!activate || !(document.activeElement instanceof HTMLElement)) {
          return;
        }

        prevFocus.current = document.activeElement;
      }, [activate]);

      const handleMountFocus =
        (callback: TransitionEnterHandler, skipped: boolean) =>
        (appearing: boolean) => {
          callback(appearing);
          const instance = ref.current;
          if (
            instance &&
            !skipped &&
            !isFocusTypeDisabled("mount") &&
            (!document.activeElement || !instance.contains(document.activeElement))
          ) {
            instance.focus();
          }
        };

      const handleUnmountFocus =
        (callback: TransitionExitHandler, skipped: boolean) => (): void => {
          callback();
          if (skipped || isFocusTypeDisabled("unmount")) {
            return;
          }

          // For some reason, the `"Enter"` keydown event fires at a different timing
          // than the Space  keydown event.
          window.requestAnimationFrame(() => {
            prevFocus.current?.focus();
          });
        };

      return {
        nodeRef: ref,
        transitionOptions: {
          nodeRef: refCallback,
          onEntering: handleMountFocus(onEntering, false),
          onEntered: handleMountFocus(
            onEntered,
            !disableTransition && !TRANSITION_CONFIG.disabled
          ),
          onExiting: handleUnmountFocus(onExiting, false),
          onExited: handleUnmountFocus(
            onExited,
            !disableTransition && !TRANSITION_CONFIG.disabled
          ),
        },
        eventHandlers: {
          onKeyDown(event) {
            onKeyDown(event);
            if (
              event.isPropagationStopped() ||
              event.key !== "Tab" ||
              isFocusTypeDisabled("keyboard")
            ) {
              return;
            }

            const { target, shiftKey, currentTarget } = event;
            const elements = getFocusableElements(currentTarget, programmatic);
            const count = elements.length;
            if (count === 0) {
              event.preventDefault();
              return;
            }

            // if the container element is the current focus, need to either focus
            // the first or last element so focus doesn't escape
            let type: FocusElementWithinType | undefined;
            if (
              count === 1 ||
              (!shiftKey &&
                (target === currentTarget || target === elements[count - 1]))
            ) {
              type = "first";
            } else if (
              shiftKey &&
              (target === currentTarget || target === elements[0])
            ) {
              type = "last";
            }

            if (type) {
              event.preventDefault();
              focusElementWithin({
                type,
                elements,
                container: currentTarget,
              });
            }
          },
        },
      };
    }