# All files / src/movement useKeyboardMovementProvider.ts

98.5% Statements 526/534
95.87% Branches 93/97
100% Functions 8/8
98.5% Lines 526/534

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
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    5351x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    955x
    955x
    1x
    1x
    332x
    332x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    94x
    2x
    92x
    364x
    270x
    270x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    356x
    356x
    364x
    364x
    364x
    364x
    135x
    135x
    135x
    135x
    135x
    135x
    135x
    135x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    363x
    363x
    363x
    75x
    75x
    75x
    363x
    363x
    364x
    364x
    364x
    364x
    364x
    364x
    364x
    96x
    45x
    51x
    268x
    364x
    364x
    364x
    364x
    51x
    51x
    51x
    51x
    51x
    51x
    51x

    51x
    51x
    51x
    51x
    51x
    51x
    14x
    14x
    37x
    37x
    37x
    37x
    23x
    23x
    37x
    37x
    37x
    51x
    16x
    16x
    16x
    37x
    37x
    37x
    37x
    37x
    37x
    364x
    171x
    171x
    15x
    15x
    15x
    156x
    156x
    169x
    114x
    171x
    137x
    137x
    19x
    19x
    19x
    19x
    19x
    145x

    19x
    19x
    19x
    19x
    19x
    19x
    19x
    19x
    19x
    107x
    6x
    2x
    2x
    2x
    2x
    2x
    2x
    6x
    4x
    4x
    4x
    4x
    4x
    6x
    19x
    145x

    19x
    19x
    19x
    107x
    6x
    6x
    19x
    133x
    17x
    145x
    2x
    2x
    19x
    19x
    19x
    19x
    19x
    19x
    364x
    85x
    85x
    85x
    85x
    55x
    55x
    55x
    55x
    55x
    55x
    1x
    1x
    54x
    54x
    54x
    54x
    35x
    35x
    35x
    35x
    35x
    35x
    54x
    55x
    37x
    37x
    54x
    54x
    54x
    54x
    54x
    54x
    85x
    85x
    85x
    85x
    85x
    85x
    85x
    85x
    85x
    85x
    13x
    13x
    72x
    72x
    72x
    72x
    85x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    72x
    72x
    72x
    72x
    20x
    20x
    85x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    71x
    71x
    71x
    71x
    71x
    71x
    71x
    71x
    85x
    15x
    15x
    15x
    15x
    69x
    15x
    15x
    15x
    15x
    15x
    15x
    56x
    56x
    83x
    85x
    85x
    85x
    85x
    52x
    42x
    27x
    85x
    85x
    18x
    18x
    38x
    38x
    38x
    85x
    4x
    4x
    4x
    4x
    85x
    10x
    10x
    10x
    10x
    34x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    38x
    38x
    38x
    364x
    364x
    364x
    364x
    364x
    364x
     "use client";
    import {
      createContext,
      useContext,
      useEffect,
      useMemo,
      useRef,
      useState,
    } from "react";
    import { getFocusableElements as defaultGetFocusableElements } from "../focus/utils.js";
    import { useUserInteractionMode } from "../interaction/UserInteractionModeProvider.js";
    import { useDir } from "../typography/WritingDirectionProvider.js";
    import { useIsomorphicLayoutEffect } from "../useIsomorphicLayoutEffect.js";
    import {
      DEFAULT_KEYBOARD_MOVEMENT,
      DEFAULT_LTR_KEYBOARD_MOVEMENT,
      DEFAULT_RTL_KEYBOARD_MOVEMENT,
    } from "./constants.js";
    import { findMatchIndex } from "./findMatchIndex.js";
    import type {
      KeyboardMovementConfig,
      KeyboardMovementConfiguration,
      KeyboardMovementContext,
      KeyboardMovementProviderImplementation,
      KeyboardMovementProviderOptions,
    } from "./types.js";
    import {
      getFirstFocusableIndex,
      getLastFocusableIndex,
      getNextFocusableIndex,
      getSearchText,
      getVirtualFocusDefaultIndex,
      isElementDisabled,
      isNotFocusable,
      isSearchableEvent,
      recalculateFocusIndex,
    } from "./utils.js";

    /**
     * @remarks \@since 5.0.0
     * @internal
     */
    const context = createContext<KeyboardMovementContext>({
      config: { current: DEFAULT_KEYBOARD_MOVEMENT },
      loopable: false,
      searchable: false,
      horizontal: false,
      includeDisabled: false,
      tabIndexBehavior: undefined,
      activeDescendantId: "",
    });
    context.displayName = "KeyboardMovement";
    export const { Provider: KeyboardMovementProvider } = context;

    /**
     * @remarks \@since 5.0.0
     * @internal
     */
    export function useKeyboardMovementContext(): Readonly<KeyboardMovementContext> {
      return useContext(context);
    }

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

    const returnNegative1 = (): number => -1;

    /**
     * Implements the custom keyboard movement behavior throughout react-md. Using
     * the "Find References" will be the best way to see example usage.
     *
     * @example
     * Default Keyboard Movement for any Focusable Element
     * ```tsx
     * import {
     *   KeyboardMovementProvider,
     *   useKeyboardMovementProvider,
     * } from "@react-md/core";
     * import type { ReactElement, ReactNode } from "react";
     *
     * function Example({ children }: { children: ReactNode }): ReactElement {
     *   const { movementContext, movementProps } = useKeyboardMovementProvider();
     *
     *   // any focusable element child can be focused with the arrow , home, and
     *   // end keys
     *   return (
     *     <KeyboardMovementProvider value={movementContext}>
     *       <div {...movementProps}>
     *         {children}
     *       </div>
     *     </KeyboardMovementProvider>
     *   );
     * }
     * ```
     *
     * @example
     * Active Descendant Movement
     * ```tsx
     * import {
     *   KeyboardMovementProvider,
     *   useKeyboardMovementContext,
     *   useKeyboardMovementProvider,
     * } from "@react-md/core";
     * import type { ReactElement, ReactNode } from "react";
     * import { useId } from "react";
     *
     * function Child(): ReactElement {
     *   const id = useId()
     *   const { activeDescendantId } = useKeyboardMovementContext();
     *
     *   return (
     *     <div
     *       {...props}
     *       id={id}
     *       className={cnb(id === activeDescendantId && "focused-class-name")}
     *     >
     *       Some Content
     *     </div>
     *   );
     * }
     *
     * function Example({ children }: { children: ReactNode }): ReactElement {
     *   const { movementContext, movementProps } = useKeyboardMovementProvider({
     *     loopable: true,
     *     searchable: true,
     *     tabIndexBehavior: "virtual",
     *   });
     *
     *   // any focusable element child can be focused with the arrow , home, and
     *   // end keys
     *   return (
     *     <KeyboardMovementProvider value={movementContext}>
     *       <div {...movementProps}>
     *         <Child />
     *         <Child />
     *         <Child />
     *       </div>
     *     </KeyboardMovementProvider>
     *   );
     * }
     * ```
     *
     * @example
     * Roving Tab Index
     * ```tsx
     * import {
     *   KeyboardMovementProvider,
     *   useKeyboardMovementContext,
     *   useKeyboardMovementProvider,
     * } from "@react-md/core";
     * import type { ReactElement, ReactNode } from "react";
     * import { useId } from "react";
     *
     * function Child(): ReactElement {
     *   const id = useId()
     *   const { activeDescendantId } = useKeyboardMovementContext();
     *
     *   return (
     *     <div
     *       {...props}
     *       id={id}
     *       tabIndex={id === activeDescendantId ? 0 : -1}
     *     >
     *       Some Content
     *     </div>
     *   );
     * }
     *
     * function Example({ children }: { children: ReactNode }): ReactElement {
     *   const { movementContext, movementProps } = useKeyboardMovementProvider({
     *     loopable: true,
     *     searchable: true,
     *     tabIndexBehavior: "roving",
     *   });
     *
     *   // any focusable element child can be focused with the arrow , home, and
     *   // end keys
     *   return (
     *     <KeyboardMovementProvider value={movementContext}>
     *       <div {...movementProps}>
     *         <Child />
     *         <Child />
     *         <Child />
     *       </div>
     *     </KeyboardMovementProvider>
     *   );
     * }
     * ```
     * @remarks \@since 6.0.0
     * @internal
     */
    export function useKeyboardMovementProvider<E extends HTMLElement>(
      options: KeyboardMovementProviderOptions<E> = {}
    ): KeyboardMovementProviderImplementation<E> {
      const {
        onClick = noop,
        onFocus = noop,
        onKeyDown = noop,
        loopable = false,
        searchable = false,
        horizontal = false,
        includeDisabled = false,
        tabIndexBehavior,
        extendKeyDown = noop,
        onFocusChange = noop,
        programmatic = includeDisabled,
        incrementKeys: propIncrementKeys,
        decrementKeys: propDecrementKeys,
        jumpToFirstKeys: propJumpToFirstKeys,
        jumpToLastKeys: propJumpToLastKeys,
        getFocusableElements = defaultGetFocusableElements,
        getDefaultFocusedIndex = returnNegative1,
      } = options;

      const isRTL = useDir().dir === "rtl";
      let defaults: Readonly<Required<KeyboardMovementConfiguration>>;
      if (horizontal) {
        defaults = isRTL
          ? DEFAULT_RTL_KEYBOARD_MOVEMENT
          : DEFAULT_LTR_KEYBOARD_MOVEMENT;
      } else {
        defaults = DEFAULT_KEYBOARD_MOVEMENT;
      }

      const incrementKeys = propIncrementKeys || defaults.incrementKeys;
      const decrementKeys = propDecrementKeys || defaults.decrementKeys;
      const jumpToFirstKeys = propJumpToFirstKeys || defaults.jumpToFirstKeys;
      const jumpToLastKeys = propJumpToLastKeys || defaults.jumpToLastKeys;

      const configuration: KeyboardMovementConfig = {
        incrementKeys,
        decrementKeys,
        jumpToFirstKeys,
        jumpToLastKeys,
      };
      const config = useRef(configuration);
      useIsomorphicLayoutEffect(() => {
        config.current = configuration;
      });

      const [activeDescendantId, setActiveDescendantId] = useState("");
      const movementContext = useMemo<KeyboardMovementContext>(
        () => ({
          config,
          loopable,
          searchable,
          horizontal,
          includeDisabled,
          tabIndexBehavior,
          activeDescendantId,
        }),
        [
          activeDescendantId,
          horizontal,
          includeDisabled,
          loopable,
          searchable,
          tabIndexBehavior,
        ]
      );
      const currentFocusIndex = useRef(-1);
      const mode = useUserInteractionMode();
      const refocus = useRef(false);

      if (process.env.NODE_ENV !== "production") {
        // this fixes issues during hot reloading and using the `useId()` hook
        // eslint-disable-next-line react-hooks/rules-of-hooks
        useEffect(() => {
          return () => {
            setActiveDescendantId("");
          };
        }, []);
      }

      return {
        movementProps: {
          "aria-activedescendant":
            tabIndexBehavior === "virtual" ? activeDescendantId : undefined,
          tabIndex:
            tabIndexBehavior === "roving"
              ? activeDescendantId
                ? -1
                : 0
              : undefined,

          // Note: This used to be on the `onFocus` event, but this causes issues in
          // Chromium browsers for drag and drop behavior
          onClick(event) {
            onClick(event);

            // This makes it so you can click an element with a mouse and then
            // keyboard navigate from that element instead of the last keyboard focus
            // element
            const { currentTarget, target } = event;
            if (target === currentTarget || !(target instanceof HTMLElement)) {
              return;
            }

            const focusables = getFocusableElements(currentTarget, programmatic);
            const focusedIndex = focusables.findIndex(
              (element) => element === target || element.contains(target)
            );
            if (focusedIndex === -1 || !focusables.length) {
              return;
            }

            currentFocusIndex.current = focusedIndex;
            const focused = focusables[focusedIndex];
            if (tabIndexBehavior) {
              setActiveDescendantId(focused.id);
            }

            // need to force focus back to the container element when using
            // aria activedescendant
            if (tabIndexBehavior === "virtual") {
              refocus.current = true;
              currentTarget.focus();
            }

            onFocusChange({
              index: focusedIndex,
              element: focused,
            });
          },
          onFocus(event) {
            onFocus(event);
            if (event.isPropagationStopped() || refocus.current) {
              refocus.current = false;
              return;
            }

            if (
              (mode !== "keyboard" && tabIndexBehavior !== "virtual") ||
              event.target !== event.currentTarget
            ) {
              return;
            }

            const focusables = getFocusableElements(
              event.currentTarget,
              programmatic
            );
            if (!focusables.length) {
              return;
            }

            let defaultFocusIndex = getDefaultFocusedIndex({
              focusables,
              includeDisabled,
            });

            // This allows my custom `getDefaultFocusedIndex` implementations to
            // have a nice fallback without having to re-implement the "focus
            // first" behavior
            if (defaultFocusIndex === -1) {
              if (tabIndexBehavior === "virtual") {
                // virtual keyboard navigation **must** always focus at least one element
                defaultFocusIndex = getVirtualFocusDefaultIndex({
                  focusables,
                  includeDisabled,
                  activeDescendantId,
                });
              } else {
                defaultFocusIndex = getFirstFocusableIndex({
                  focusables,
                  includeDisabled,
                });
              }
            }

            if (defaultFocusIndex === -1) {
              return;
            }

            currentFocusIndex.current = defaultFocusIndex;
            const focused = focusables[defaultFocusIndex];
            if (tabIndexBehavior) {
              setActiveDescendantId(focused.id);
            }

            if (tabIndexBehavior !== "virtual") {
              focused.focus();
            } else {
              focused.scrollIntoView({ block: "nearest" });
            }

            onFocusChange({
              index: defaultFocusIndex,
              element: focused,
            });
          },
          onKeyDown(event) {
            onKeyDown(event);
            const { currentTarget } = event;

            const setFocusIndex = (
              index: number,
              focusables: readonly HTMLElement[]
            ): void => {
              event.preventDefault();
              event.stopPropagation();
              if (currentFocusIndex.current === index || index === -1) {
                return;
              }

              currentFocusIndex.current = index;
              const focused = focusables[index];
              if (tabIndexBehavior) {
                focused.scrollIntoView({
                  block: "nearest",
                  inline: "nearest",
                });
                setActiveDescendantId(focused.id);
              }

              if (tabIndexBehavior !== "virtual") {
                focused.focus();
              }

              onFocusChange({
                index,
                element: focused,
              });
            };

            extendKeyDown({
              event,
              setFocusIndex,
              currentFocusIndex,
              setActiveDescendantId,
              ...movementContext,
            });

            if (event.isPropagationStopped()) {
              return;
            }

            // TODO: Figure this part out. This is currently required for the tree
            // movement when the asterisk key is pressed. There might be other cases
            // as well.
            if (currentFocusIndex.current === -1) {
              currentFocusIndex.current = recalculateFocusIndex({
                focusables: getFocusableElements(currentTarget, programmatic),
                includeDisabled,
                tabIndexBehavior,
                activeDescendantId,
              });
            }

            const { key, shiftKey } = event;
            if (
              tabIndexBehavior === "virtual" &&
              activeDescendantId &&
              (key === " " || key === "Enter")
            ) {
              if (key === " ") {
                event.preventDefault();
              }

              const focusables = getFocusableElements(currentTarget, programmatic);
              const activeElement = focusables[currentFocusIndex.current];
              if (!activeElement || isElementDisabled(activeElement)) {
                return;
              }

              activeElement.click();
              return;
            }

            const {
              incrementKeys,
              decrementKeys,
              jumpToFirstKeys,
              jumpToLastKeys,
            } = config.current;

            if (searchable && isSearchableEvent(event)) {
              const focusables = getFocusableElements(currentTarget, programmatic);
              const index = findMatchIndex({
                value: key,
                values: focusables.map((element) =>
                  getSearchText(element, !isNotFocusable(element, includeDisabled))
                ),
                startIndex: shiftKey ? -1 : currentFocusIndex.current,
              });
              setFocusIndex(index, focusables);
              return;
            }

            const jumpToFirst = jumpToFirstKeys.includes(key);
            const jumpToLast = !jumpToFirst && jumpToLastKeys.includes(key);
            const increment =
              !jumpToFirst && !jumpToLast && incrementKeys.includes(key);
            const decrement =
              !jumpToFirst &&
              !jumpToLast &&
              !increment &&
              decrementKeys.includes(key);

            if (!jumpToFirst && !jumpToLast && !increment && !decrement) {
              return;
            }
            const focusables = getFocusableElements(currentTarget, programmatic);

            let index: number;
            if (jumpToFirst) {
              index = getFirstFocusableIndex({
                focusables,
                includeDisabled,
              });
            } else if (jumpToLast) {
              index = getLastFocusableIndex({
                focusables,
                includeDisabled,
              });
            } else {
              index = getNextFocusableIndex({
                loopable,
                increment,
                focusables,
                includeDisabled,
                currentFocusIndex: currentFocusIndex.current,
              });
            }

            setFocusIndex(index, focusables);
          },
        },
        movementContext,
        currentFocusIndex,
        setActiveDescendantId,
      };
    }