All files / focus focus.ts

97.05% Statements 66/68
96.96% Branches 64/66
94.11% Functions 16/17
100% Lines 57/57

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      5x                   5x 100x         10x 90x 90x 100x 87x 100x         20x 52x   20x 34x 9x 6x 24x           12x 6x                     29x         29x 4x 4x 3x     29x 29x         38x 39x   38x 38x       8x 9x 7x 1x 1x 1x   6x 6x 6x 6x 7x   6x 3x 3x 3x 3x 3x         38x 38x 38x 38x           171x 24x 24x               212x 212x 68x 68x    
import { isHTMLInputElement, listen } from '../dom/dom';
import type { Unsubscribe } from '../core/types';
 
const selector = [
  'a[href]',
  'button:not([disabled])',
  'input:not([disabled]):not([type="hidden"])',
  'select:not([disabled])',
  'textarea:not([disabled])',
  '[tabindex]:not([tabindex="-1"])',
  '[contenteditable="true"]',
].join(',');
 
const isUnavailable = (element: HTMLElement): boolean => {
  if (
    element.hidden ||
    element.closest('[hidden], [inert], [aria-hidden="true"]') ||
    ('disabled' in element && element.disabled === true)
  )
    return true;
  const closedDetails = element.closest('details:not([open])');
  const summary = closedDetails?.querySelector<HTMLElement>(':scope > summary');
  if (closedDetails && !summary?.contains(element)) return true;
  const style = element.ownerDocument.defaultView?.getComputedStyle(element);
  return style?.display === 'none' || style?.visibility === 'hidden';
};
 
/** Returns visible, enabled elements that participate in sequential focus navigation. @internal */
export function getTabbableElements(container: Element): readonly HTMLElement[] {
  const candidates = [...container.querySelectorAll<HTMLElement>(selector)].filter(
    (element) => !isUnavailable(element) && element.getClientRects().length > 0,
  );
  return candidates.filter((element) => {
    if (!isHTMLInputElement(element)) return true;
    if (element.type !== 'radio' || !element.name) return true;
    const group = candidates.filter(
      (candidate): candidate is HTMLInputElement =>
        isHTMLInputElement(candidate) &&
        candidate.type === 'radio' &&
        candidate.name === element.name &&
        candidate.form === element.form,
    );
    const checked = group.find((radio) => radio.checked);
    return checked ? checked === element : group[0] === element;
  });
}
 
/** Focuses a preferred target, first tabbable descendant, or focusable fallback container. @internal */
export function focusInitial(
  container: HTMLElement,
  preferred?: HTMLElement | null,
  ownFallbackCleanup?: (cleanup: Unsubscribe) => void,
): HTMLElement {
  const candidate =
    preferred?.isConnected &&
    (preferred === container || container.contains(preferred)) &&
    !isUnavailable(preferred)
      ? preferred
      : (getTabbableElements(container)[0] ?? container);
  if (candidate === container && !container.hasAttribute('tabindex')) {
    container.tabIndex = -1;
    ownFallbackCleanup?.(() => {
      if (container.getAttribute('tabindex') === '-1') container.removeAttribute('tabindex');
    });
  }
  candidate.focus({ preventScroll: true });
  return candidate;
}
 
/** Contains Tab focus inside a scope until its returned cleanup is called. @internal */
export function trapFocus(container: HTMLElement, branches: readonly Element[] = []): Unsubscribe {
  const scopes = [...new Set<Element>([container, ...branches])].filter(
    (scope) => scope.ownerDocument === container.ownerDocument,
  );
  const fallbackCleanups = new Set<Unsubscribe>();
  const releaseListener = listen<KeyboardEvent>(
    container.ownerDocument,
    'keydown',
    (event) => {
      if (event.key !== 'Tab') return;
      const tabbables = [...new Set(scopes.flatMap((scope) => getTabbableElements(scope)))];
      if (tabbables.length === 0) {
        event.preventDefault();
        focusInitial(container, undefined, (cleanup) => fallbackCleanups.add(cleanup));
        return;
      }
      const first = tabbables[0];
      const last = tabbables.at(-1);
      const active = container.ownerDocument.activeElement;
      const containsActive = scopes.some(
        (scope) => active !== null && (scope === active || scope.contains(active)),
      );
      if (event.shiftKey && (active === first || !containsActive)) {
        event.preventDefault();
        last?.focus();
      } else Eif (!event.shiftKey && (active === last || !containsActive)) {
        event.preventDefault();
        first?.focus();
      }
    },
    true,
  );
  return () => {
    releaseListener();
    for (const cleanup of fallbackCleanups) cleanup();
    fallbackCleanups.clear();
  };
}
 
/** Restores focus when the target is still connected and focusable. @internal */
export function restoreFocus(target: HTMLElement | null | undefined): boolean {
  if (!target?.isConnected || isUnavailable(target)) return false;
  target.focus({ preventScroll: true });
  return target.ownerDocument.activeElement === target;
}
 
/** Moves DOM focus among registered elements using a shared item ID. @internal */
export function focusById(
  elements: ReadonlyMap<string, HTMLElement>,
  id: string | undefined,
): boolean {
  const target = id ? elements.get(id) : undefined;
  if (!target?.isConnected) return false;
  target.focus({ preventScroll: true });
  return true;
}