All files / src/hooks useFocusTrap.ts

90.38% Statements 47/52
78.26% Branches 18/23
100% Functions 2/2
90.38% Lines 47/52

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 581x   1x 1x 1x 1x 1x 1x 1x 1x   1x 134x 22x 22x   22x 22x 22x 22x 22x   22x 101x 2x 2x 2x 2x 101x 96x 96x 3x 5x       3x 3x 101x     101x 1x 1x 5x 1x 1x 1x 101x   22x 22x 22x 22x 22x 134x 134x  
import { useEffect, type RefObject } from "react";
 
const FOCUSABLE = [
  "a[href]",
  "button:not([disabled])",
  "input:not([disabled])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  '[tabindex]:not([tabindex="-1"])',
].join(",");
 
export function useFocusTrap(ref: RefObject<HTMLElement | null>, onClose: () => void): void {
  useEffect(() => {
    const node = ref.current;
    const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
 
    if (node && !node.contains(document.activeElement)) {
      const preferred = node.querySelector<HTMLElement>("[data-autofocus]");
      const first = preferred ?? node.querySelector<HTMLElement>(FOCUSABLE) ?? node;
      first.focus();
    }
 
    function onKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape") {
        event.preventDefault();
        onClose();
        return;
      }
      if (event.key !== "Tab" || !node) {
        return;
      }
      const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (items.length === 0) {
        event.preventDefault();
        return;
      }
      const first = items[0];
      const last = items[items.length - 1];
      if (!first || !last) {
        return;
      }
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    }
 
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      previous?.focus();
    };
  }, [ref, onClose]);
}