# All files / src/focus utils.ts

86.92% Statements 133/153
69.23% Branches 9/13
50% Functions 2/4
86.92% Lines 133/153

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
    1541x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    119x
    119x
    119x
    119x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    56x
    56x
    56x
    56x
    56x
    56x
    56x
    56x
    56x
    56x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    4x
    4x

    4x
    4x
    4x
    3x
    4x
    1x
    1x

    4x
    4x

    4x
    4x
    4x
    4x
     const queries = [
      'input:not([type="hidden"]):not([disabled])',
      "button:not([disabled])",
      "textarea:not([disabled])",
      "select:not([disabled])",
      "a[href]",
      "area[href]",
      "[tabindex]",
    ] as const;

    /**
     * A query selector to find elements that are programmatically focusable.
     *
     * Example:
     *
     * ```ts
     * const focusableElements = document.querySelectorAll(PROGRAMMATICALLY_FOCUSABLE);
     * // do something with elements
     * ```
     */
    export const PROGRAMMATICALLY_FOCUSABLE = queries.join(",");

    /**
     * A query selector to find elements that are focusable only with tab and shift+tab.
     *
     * Example:
     *
     * ```ts
     * const focusableElements = document.querySelectorAll(TAB_FOCUSABLE);
     * // do something with elements
     * ```
     *
     * @remarks \@since 6.0.0 This was updated to remove ALL elements that have a
     * `tabindex="-1"` applied instead of only elements that had a manual tab index
     * applied.
     */
    export const TAB_FOCUSABLE = queries.reduce((fullQuery, query) => {
      const prefix = `${fullQuery}${fullQuery ? "," : ""}`;
      const notProgrammaticQuery = `${query}:not([tabindex="-1"])`;

      return `${prefix}${notProgrammaticQuery}`;
    }, "");

    /**
     * A simple util that will find all the tab focusable elements within a
     * container element.  The container should normally be a specific HTMLElement,
     * but it can also be the entire document if you want to find **all** focusable
     * elements within your page.
     *
     * @remarks
     * \@since 6.0.0 This function will be used for all keyboard focus behavior
     * instead of trying to use refs. I did some performance testing in Firefox and
     * Chrome and the `querySelectorAll` takes 4ms with 5000 elements for my use
     * cases. There is more of a performance issue around rendering all 5000
     * elements and since this is only used for specific keydown events, this is
     * good enough for me.
     *
     * @param container - The container element/document to find focusable elements
     * within.
     * @param programmatic - Boolean if programmatically focusable elements should be
     * included instead of only tab focusable.
     * @returns A list of HTMLElements that are focusable within the container.
     */
    export function getFocusableElements(
      container: HTMLElement | Document,
      programmatic = false
    ): readonly HTMLElement[] {
      // spread operator is faster than Array.from
      return [
        ...container.querySelectorAll<HTMLElement>(
          programmatic ? PROGRAMMATICALLY_FOCUSABLE : TAB_FOCUSABLE
        ),
      ];
    }

    /**
     * Attempts to find the first focusable element within a container.
     *
     * @remarks \@since 6.0.0
     * @param container - The container element/document to find focusable elements
     * within.
     * @param programmatic - Boolean if programmatically focusable elements should be
     * included instead of only tab focusable.
     * @returns A list of HTMLElements that are focusable within the container.
     */
    export function getFocusableElement(
      container: HTMLElement | Document,
      programmatic = false
    ): HTMLElement | null {
      return container.querySelector<HTMLElement>(
        programmatic ? PROGRAMMATICALLY_FOCUSABLE : TAB_FOCUSABLE
      );
    }

    /**
     * An element can be tab focused if it is:
     * - an anchor or area with an `href`
     * - a non-disabled `input` element that is not `type="hidden"`
     * - a non-disabled `button`, `textarea`, or `select` element
     * - an element with a `tabIndex >= 0`
     *
     * An element can be noted as "programmatically focusable only"  has the above
     * rules, but the `tabIndex` will be set to `-1`.
     *
     * @remarks \@since 2.8.0
     */
    export type ElementFocusType = "tab" | "programmatic";

    export function isFocusable(
      element: HTMLElement | Document | Window,
      type: ElementFocusType = "programmatic"
    ): element is HTMLElement {
      const selector = type === "tab" ? TAB_FOCUSABLE : PROGRAMMATICALLY_FOCUSABLE;

      return "matches" in element && element.matches(selector);
    }

    export type FocusElementWithinType =
      | "first"
      | "last"
      | "query"
      | "self"
      | "none";

    export interface FocusElementWithinOptions {
      type: FocusElementWithinType;
      query?: string;
      elements: readonly HTMLElement[];
      container: HTMLElement | Document;
    }

    export function focusElementWithin(options: FocusElementWithinOptions): void {
      const { type, query = "", container, elements } = options;
      if (type === "none") {
        return;
      }

      let element: HTMLElement | null = null;
      if (type === "first") {
        [element] = elements;
      } else if (type === "last") {
        element = elements[elements.length - 1];
      } else if (type === "query") {
        element = document.querySelector<HTMLElement>(query);
      }

      if (!element && isFocusable(container)) {
        element = container;
      }

      // TODO: Why did I add preventScroll?
      element?.focus();
    }